### Warning
This is a long post. It wasn't meant to be this way, but reaction diffusion equations proved to be too damn interesting not to write a lot about. To try and understand the system, I do some maths and some programming. Be warned, the maths isn't rigorous and the code isn't the most efficient. This is a deliberate choice. My goal is to try and understand the system, and along the way learn to create images like this

# Turing Patterns

In 1952, [Turing](https://en.wikipedia.org/wiki/Alan_Turing) published a paper called ["The Chemical Basis of Morphogenesis"](http://www.dna.caltech.edu/courses/cs191/paperscs191/turing.pdf) suggesting a possible mechanism for how a simple set of chemical reactions could lead to the formation of stripes, spots and other patterns we see on animals. It is a surprisingly readable paper that covers some maths, some chemistry, some numerical modelling and ties it all together to try and answer a biological question.

At the core of the paper are a set of partial differential equations known as [reaction-diffusion equations](https://en.wikipedia.org/wiki/Reaction%E2%80%93diffusion_system). Turing's analysis shows that in certain regimes systems that obey these equations are unstable to small perturbations, leading to the growth of large scale patterns.

If you have only a basic understanding of chemistry (like I do) this might be surprising. Most chemical reactions I've seen involve homogeneous concentrations of reagents, reacting to create the final products, often described by a reaction equation like

$A + B \rightarrow C + D$

In this simplified model there is no room for pattern formation, because haven't included any description about how concentrations of the different chemicals vary in space. Once we take into account these differences, a much richer set of behaviours is possible.

In this post, I am going explore the system described in the paper.

## Reaction Diffusion Equations

Reaction-Diffusion equations are a class of partial differential equations whose dynamics are governed by two terms: a diffusion part and a reaction part. We will be looking at the two component case, which takes the form

$\frac{\partial a(x,t)}{\partial t} = D_{a}\frac{\partial^{2} a(x,t)}{\partial x^{2}} + R_{a}(a(x,t),b(x,t))$

$\frac{\partial b(x,t)}{\partial t} = D_{b}\frac{\partial^{2} b(x,t)}{\partial x^{2}} + R_{b}(a(x,t),b(x,t))$

Where the $a(x,t)$ and $b(x,t)$ describe the concentration of chemicals $a$ and $b$ at position $x$ and time $t$. The functions $R_{a}$ and $R_{b}$ determine how the concentrations change due to interspecies reactions and $D_{a}$ and $D_{b}$ are the diffusion coefficients.

### Diffusion

The diffusion part of the equations causes areas of high concentration to spread out to areas of low concentration, while conserving the total amount of the chemical. To get a feel for what's happening, let's focus the equation

$ \frac{\partial a(x,t)}{\partial t} = D_{a}\frac{\partial^{2} a(x,t)}{\partial x^{2}} $

If this looks familiar, it is because it appears in a number of different areas of science and maths. A few are: the [diffusion equation](https://en.wikipedia.org/wiki/Diffusion_equation), the [heat equation](https://en.wikipedia.org/wiki/Heat_equation) and [Brownian motion](https://en.wikipedia.org/wiki/Brownian_motion).

It has an analytic solution, which for initial Gaussian distribution is

$ a(x,t) = \frac{a_{0}}{\sqrt{2\pi(\sigma_{0}^{2} + 2 D_{a} t)}} \exp\left(-\frac{x^{2}}{2(\sigma_{0}^{2} +  2 D_{a} t)}\right)$

A "spreading out", or diffusion over time, as the name suggests.

### Simulating equations

If you've got this far, you might have noticed that this is written in a [jupyter notebook](http://jupyter.org/). This allows us to mix code with writing, so we don't just have to look at an equation to understand how it behaves - we can simulate it directly.

To simulate the PDEs, I'm going to use the [explicit finite-difference method](https://en.wikipedia.org/wiki/Finite_difference_method#Example:_The_heat_equation). It is not the best numerical method to use, but it is easy to code, and provided we keep the time step small enough it will be stable.

Under this scheme, we approximate the time derivative as

$$
\frac{\partial a(x,t)}{\partial t} \approx \frac{1}{dt}(a_{x,t+1} - a_{x,t})
$$

And the spatial part of the derivative (which is usually know as the [Laplacian](https://en.wikipedia.org/wiki/Laplace_operator)) as

$$
\frac{\partial^{2} a(x,t)}{\partial x^{2}} \approx \frac{1}{dx^{2}}(a_{x+1,t} + a_{x-1,t} - 2a_{x,t})
$$

Putting it all together, for the diffusion part of the equation we get.

$$
a_{x,t+1} = a_{x,t} + dt\left(  \frac{D_{a}}{dx^{2}}(a_{x+1,t} + a_{x-1,t} - 2a_{x,t})  \right)
$$

Let's start by defining some functions to take care of the spatial derivatives. We will be using periodic boundary conditions throughout our exploration, which are easy to implement in numpy using its [roll](https://docs.scipy.org/doc/numpy-1.12.0/reference/generated/numpy.roll.html) function.

```python
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import HTML

# I'm using seaborn for it's fantastic default styles
import seaborn as sns
sns.set_style("whitegrid")

%matplotlib inline
%load_ext autoreload
%autoreload 2

from tutils import BaseStateSystem
```

```python
def laplacian1D(a, dx):
    return (
        - 2 * a
        + np.roll(a,1,axis=0)
        + np.roll(a,-1,axis=0)
    ) / (dx ** 2)

def laplacian2D(a, dx):
    return (
        - 4 * a
        + np.roll(a,1,axis=0)
        + np.roll(a,-1,axis=0)
        + np.roll(a,+1,axis=1)
        + np.roll(a,-1,axis=1)
    ) / (dx ** 2)
```

To aid in generating visualisations, I've written a base class which updates and plots a system based on some notion of state. There's nothing specific about the reaction diffusion equations encoded in it, so I'm not going to go into any detail about it. You can find the full code for it, along with this notebook on github [here](https://github.com/ijmbarr/turing-patterns). It uses [matplotlib's animation](http://matplotlib.org/api/animation_api.html) functionality to plot the output as a gif.

All together we can simulate the effect of the diffusion equation:

```python
class OneDimensionalDiffusionEquation(BaseStateSystem):
    def __init__(self, D):
        self.D = D
        self.width = 1000
        self.dx = 10 / self.width
        self.dt = 0.9 * (self.dx ** 2) / (2 * D)
        self.steps = int(0.1 / self.dt)

    def initialise(self):
        self.t = 0
        self.X = np.linspace(-5,5,self.width)
        self.a = np.exp(-self.X**2)

    def update(self):
        for _ in range(self.steps):
            self.t += self.dt
            self._update()

    def _update(self):
        La = laplacian1D(self.a, self.dx)
        delta_a = self.dt * (self.D * La)
        self.a += delta_a

    def draw(self, ax):
        ax.clear()
        ax.plot(self.X,self.a, color="r")
        ax.set_ylim(0,1)
        ax.set_xlim(-5,5)
        ax.set_title("t = {:.2f}".format(self.t))

one_d_diffusion = OneDimensionalDiffusionEquation(D=1)
```

```python
one_d_diffusion.plot_time_evolution("diffusion.html")
HTML("diffusion.html")
```

<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/
css/font-awesome.min.css">

    <input id="_anim_slider4b47d85b7acd412e9ad6255668c6503f" type="range" class="anim-slider"
           name="points" min="0" max="1" step="1" value="0"
           oninput="anim4b47d85b7acd412e9ad6255668c6503f.set_frame(parseInt(this.value));"></input>

      <button onclick="anim4b47d85b7acd412e9ad6255668c6503f.slower()"></button>
      <button onclick="anim4b47d85b7acd412e9ad6255668c6503f.first_frame()">
          </button>
      <button onclick="anim4b47d85b7acd412e9ad6255668c6503f.previous_frame()">
          </button>
      <button onclick="anim4b47d85b7acd412e9ad6255668c6503f.reverse_animation()">
          </button>
      <button onclick="anim4b47d85b7acd412e9ad6255668c6503f.pause_animation()">
          </button>
      <button onclick="anim4b47d85b7acd412e9ad6255668c6503f.play_animation()">
          </button>
      <button onclick="anim4b47d85b7acd412e9ad6255668c6503f.next_frame()">
          </button>
      <button onclick="anim4b47d85b7acd412e9ad6255668c6503f.last_frame()">
          </button>
      <button onclick="anim4b47d85b7acd412e9ad6255668c6503f.faster()"></button>

    <form action="#n" name="_anim_loop_select4b47d85b7acd412e9ad6255668c6503f" class="anim-state">
      <input type="radio" name="state" value="once" id="_anim_radio1_4b47d85b7acd412e9ad6255668c6503f"
             >
      Once
      <input type="radio" name="state" value="loop" id="_anim_radio2_4b47d85b7acd412e9ad6255668c6503f"
             checked>
      Loop
      <input type="radio" name="state" value="reflect" id="_anim_radio3_4b47d85b7acd412e9ad6255668c6503f"
             >
      Reflect
    </form>

As expected - the diffusion equation causes the the concentration to "spread out".

### Reaction

Interactions between the two chemical components are introduced via the functions $R_{a}$ and $R_{b}$. These functions only depend on the local concentration of each of the chemicals. Their exact form will depend on the chemicals involved, but it is possible to show that Turing patterns are observed for a whole class of different equations.

The one thing we will require from these equations is that they reach a stable equilibrium when the concentrations of the chemicals involved are completely homogeneous. This means that there exists concentrations of $a$ and $b$ such that

$R_a(a_{0}, b_{0}) = 0$

$R_{b}(a_{0}, b_{0}) = 0$

The fact that we require this to hold will make the later instability more suprising.

For the reaction equations, I'm going to use the [FitzHugh–Nagumo equation](https://en.wikipedia.org/wiki/FitzHugh%E2%80%93Nagumo_model)

$R_a(a, b) = a - a^{3} - b + \alpha$

$R_{b}(a, b) = \beta (a - b)$

Where $\alpha$ and $\beta$ are constants.

Let's see how it behaves

```python
class ReactionEquation(BaseStateSystem):
    def __init__(self, Ra, Rb):
        self.Ra = Ra
        self.Rb = Rb
        self.dt = 0.01
        self.steps = int(0.1 / self.dt)

    def initialise(self):
        self.t = 0
        self.a = 0.1
        self.b = 0.7
        self.Ya = []
        self.Yb = []
        self.X = []

    def update(self):
        for _ in range(self.steps):
            self.t += self.dt
            self._update()

    def _update(self):
        delta_a = self.dt * self.Ra(self.a,self.b)
        delta_b = self.dt * self.Rb(self.a,self.b)

        self.a += delta_a
        self.b += delta_b

    def draw(self, ax):
        ax.clear()

        self.X.append(self.t)
        self.Ya.append(self.a)
        self.Yb.append(self.b)

        ax.plot(self.X,self.Ya, color="r", label="A")
        ax.plot(self.X,self.Yb, color="b", label="B")
        ax.legend()

        ax.set_ylim(0,1)
        ax.set_xlim(0,5)
        ax.set_xlabel("t")
        ax.set_ylabel("Concentrations")

alpha, beta =  0.2, 5

def Ra(a,b): return a - a ** 3 - b + alpha
def Rb(a,b): return (a - b) * beta

one_d_reaction = ReactionEquation(Ra, Rb)

```

```python
one_d_reaction.plot_time_evolution("reaction.html",n_steps=50)
HTML("reaction.html")
```

<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/
css/font-awesome.min.css">

    <input id="_anim_slidere238a1512c364d419f4a8fa4f7ea295f" type="range" class="anim-slider"
           name="points" min="0" max="1" step="1" value="0"
           oninput="anime238a1512c364d419f4a8fa4f7ea295f.set_frame(parseInt(this.value));"></input>

      <button onclick="anime238a1512c364d419f4a8fa4f7ea295f.slower()"></button>
      <button onclick="anime238a1512c364d419f4a8fa4f7ea295f.first_frame()">
          </button>
      <button onclick="anime238a1512c364d419f4a8fa4f7ea295f.previous_frame()">
          </button>
      <button onclick="anime238a1512c364d419f4a8fa4f7ea295f.reverse_animation()">
          </button>
      <button onclick="anime238a1512c364d419f4a8fa4f7ea295f.pause_animation()">
          </button>
      <button onclick="anime238a1512c364d419f4a8fa4f7ea295f.play_animation()">
          </button>
      <button onclick="anime238a1512c364d419f4a8fa4f7ea295f.next_frame()">
          </button>
      <button onclick="anime238a1512c364d419f4a8fa4f7ea295f.last_frame()">
          </button>
      <button onclick="anime238a1512c364d419f4a8fa4f7ea295f.faster()"></button>

    <form action="#n" name="_anim_loop_selecte238a1512c364d419f4a8fa4f7ea295f" class="anim-state">
      <input type="radio" name="state" value="once" id="_anim_radio1_e238a1512c364d419f4a8fa4f7ea295f"
             >
      Once
      <input type="radio" name="state" value="loop" id="_anim_radio2_e238a1512c364d419f4a8fa4f7ea295f"
             checked>
      Loop
      <input type="radio" name="state" value="reflect" id="_anim_radio3_e238a1512c364d419f4a8fa4f7ea295f"
             >
      Reflect
    </form>

The system is stable, and stabilises to $a = b = \sqrt[3]{\alpha}$.

## Full Model

We now have two parts to the reaction diffusion equation: a diffusion term that "spreads" out concentration and a reaction part the equalises the two concentrations. It feels like these two together should create a stable system, so it is surprising that we can end up with patterns.

But enough with the preliminaries, let's take a look at some of the patterns formed.

```python
def random_initialiser(shape):
    return(
        np.random.normal(loc=0, scale=0.05, size=shape),
        np.random.normal(loc=0, scale=0.05, size=shape)
    )

class OneDimensionalRDEquations(BaseStateSystem):
    def __init__(self, Da, Db, Ra, Rb,
                 initialiser=random_initialiser,
                 width=1000, dx=1,
                 dt=0.1, steps=1):

        self.Da = Da
        self.Db = Db
        self.Ra = Ra
        self.Rb = Rb

        self.initialiser = initialiser
        self.width = width
        self.dx = dx
        self.dt = dt
        self.steps = steps

    def initialise(self):
        self.t = 0
        self.a, self.b = self.initialiser(self.width)

    def update(self):
        for _ in range(self.steps):
            self.t += self.dt
            self._update()

    def _update(self):

        # unpack so we don't have to keep writing "self"
        a,b,Da,Db,Ra,Rb,dt,dx = (
            self.a, self.b,
            self.Da, self.Db,
            self.Ra, self.Rb,
            self.dt, self.dx
        )

        La = laplacian1D(a, dx)
        Lb = laplacian1D(b, dx)

        delta_a = dt * (Da * La + Ra(a,b))
        delta_b = dt * (Db * Lb + Rb(a,b))

        self.a += delta_a
        self.b += delta_b

    def draw(self, ax):
        ax.clear()
        ax.plot(self.a, color="r", label="A")
        ax.plot(self.b, color="b", label="B")
        ax.legend()
        ax.set_ylim(-1,1)
        ax.set_title("t = {:.2f}".format(self.t))

Da, Db, alpha, beta = 1, 100, -0.005, 10

def Ra(a,b): return a - a ** 3 - b + alpha
def Rb(a,b): return (a - b) * beta

width = 100
dx = 1
dt = 0.001

OneDimensionalRDEquations(
    Da, Db, Ra, Rb,
    width=width, dx=dx, dt=dt,
    steps=100
).plot_time_evolution("1dRD.html", n_steps=150)
HTML("1dRD.html")
```

<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/
css/font-awesome.min.css">

    <input id="_anim_slider93706b35fcb9482ca95bfa1696a5733e" type="range" class="anim-slider"
           name="points" min="0" max="1" step="1" value="0"
           oninput="anim93706b35fcb9482ca95bfa1696a5733e.set_frame(parseInt(this.value));"></input>

      <button onclick="anim93706b35fcb9482ca95bfa1696a5733e.slower()"></button>
      <button onclick="anim93706b35fcb9482ca95bfa1696a5733e.first_frame()">
          </button>
      <button onclick="anim93706b35fcb9482ca95bfa1696a5733e.previous_frame()">
          </button>
      <button onclick="anim93706b35fcb9482ca95bfa1696a5733e.reverse_animation()">
          </button>
      <button onclick="anim93706b35fcb9482ca95bfa1696a5733e.pause_animation()">
          </button>
      <button onclick="anim93706b35fcb9482ca95bfa1696a5733e.play_animation()">
          </button>
      <button onclick="anim93706b35fcb9482ca95bfa1696a5733e.next_frame()">
          </button>
      <button onclick="anim93706b35fcb9482ca95bfa1696a5733e.last_frame()">
          </button>
      <button onclick="anim93706b35fcb9482ca95bfa1696a5733e.faster()"></button>

    <form action="#n" name="_anim_loop_select93706b35fcb9482ca95bfa1696a5733e" class="anim-state">
      <input type="radio" name="state" value="once" id="_anim_radio1_93706b35fcb9482ca95bfa1696a5733e"
             >
      Once
      <input type="radio" name="state" value="loop" id="_anim_radio2_93706b35fcb9482ca95bfa1696a5733e"
             checked>
      Loop
      <input type="radio" name="state" value="reflect" id="_anim_radio3_93706b35fcb9482ca95bfa1696a5733e"
             >
      Reflect
    </form>

A pattern of stripes.

We can see that same behavior in two dimensions:

```python
class TwoDimensionalRDEquations(BaseStateSystem):
    def __init__(self, Da, Db, Ra, Rb,
                 initialiser=random_initialiser,
                 width=1000, height=1000,
                 dx=1, dt=0.1, steps=1):

        self.Da = Da
        self.Db = Db
        self.Ra = Ra
        self.Rb = Rb

        self.initialiser = initialiser
        self.width = width
        self.height = height
        self.shape = (width, height)
        self.dx = dx
        self.dt = dt
        self.steps = steps

    def initialise(self):
        self.t = 0
        self.a, self.b = self.initialiser(self.shape)

    def update(self):
        for _ in range(self.steps):
            self.t += self.dt
            self._update()

    def _update(self):

        # unpack so we don't have to keep writing "self"
        a,b,Da,Db,Ra,Rb,dt,dx = (
            self.a, self.b,
            self.Da, self.Db,
            self.Ra, self.Rb,
            self.dt, self.dx
        )

        La = laplacian2D(a, dx)
        Lb = laplacian2D(b, dx)

        delta_a = dt * (Da * La + Ra(a,b))
        delta_b = dt * (Db * Lb + Rb(a,b))

        self.a += delta_a
        self.b += delta_b

    def draw(self, ax):
        ax[0].clear()
        ax[1].clear()

        ax[0].imshow(self.a, cmap='jet')
        ax[1].imshow(self.b, cmap='brg')

        ax[0].grid(b=False)
        ax[1].grid(b=False)

        ax[0].set_title("A, t = {:.2f}".format(self.t))
        ax[1].set_title("B, t = {:.2f}".format(self.t))

    def initialise_figure(self):
        fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(12,6))
        return fig, ax

Da, Db, alpha, beta = 1, 100, -0.005, 10

def Ra(a,b): return a - a ** 3 - b + alpha
def Rb(a,b): return (a - b) * beta

width = 100
dx = 1
dt = 0.001

TwoDimensionalRDEquations(
    Da, Db, Ra, Rb,
    width=width, height=width,
    dx=dx, dt=dt, steps=100
).plot_evolution_outcome("2dRD.png", n_steps=150)
```

[](http://www.degeneratestate.org/static/turing-patterns/2dRD.gif)

(It is possible to animate the formation of these patterns using a similar method call as in the one-dimensional case above. The resulting gifs are quite impressive, but also large, so they are not directly included here. However, if you click on the image it will take you to the animation)

It turns out this behaviour is common to a lot of reaction-diffusion equations, not just the ones presented here.

So how does this happen? To understand, we are going to need to do some maths.

## Stability Analysis

Let's return to the original equations. We've seen that for certain conditions, pattern formations occurs.

Unfortunately, solving the equations directly for non-linear reaction functions is often not possible. Instead we can look at what happens when the the system is perturbed slightly from equilibrium.

### Linearising the Equations

We start by assuming there is some concentrations, $a_{0}$ and $b_{0}$, for which the system is stable. This means that
 - $R_{a}(a_{0},b_{0}) = 0$
 - $R_{b}(a_{0},b_{0}) = 0$

Around these solutions, we look at the time dependence of small perturbations around these values
 - $x = a - a_{0}$
 - $y = b - b_{0}$

And linearise the reaction equations
 - $R_{a}(a,b) \approx r_{aa}x + r_{ab}y$
 - $R_{b}(a,b) \approx r_{ba}x + r_{bb}y$

where $r_{ij} = \frac{\partial R_{i}}{\partial j}$.

These approximations give us a set of linear equations, written in vector form as

$\dot{\mathbf{x}} = D\nabla^{2} \mathbf{x} + R \mathbf{x}$

Where $R = \left(\begin{matrix} r_{11} & r_{12} \\ r_{21} & r_{22}\end{matrix}\right)$ and $D = \left(\begin{matrix} D_{a} & 0 \\ 0 & D_{b}\end{matrix}\right)$

### Fourier Transform
If we impose periodic boundary conditions to this equation, a natural solution can be found by applying a [Fourier Transformation](https://acko.net/files/gltalks/toolsforthought/) to $\mathbf{x}$. If we call the reciprocal coordinate $k$, and the Fourier transform of $\mathbf{x}$ as $\tilde{\mathbf{x}}$, then the transformed equation is

$\dot{\tilde{\mathbf{x}}} = (R - k^{2}D) \tilde{\mathbf{x}}$

Which, has solutions of the form

$\tilde{\mathbf{x}}(t) = \tilde{\mathbf{x}}(0) e^{\omega t}$

To find $\omega$ we plug this solution back into our transformed equation to get

$\omega \tilde{\mathbf{x}} = (R - k^{2}D) \tilde{\mathbf{x}}$

Showing that $\omega$ is just the eigenvalue of $(R - k^{2}D)$.

### Stability

We now have an equation for the time dependence of our system in the Fourier domain. Using it, we can now discuss what we mean by _stability_. Our system is considered stable if small perturbations around the homogeneous do not cause it to move further away from the stable solutions.

In terms of our solution, $\tilde{\mathbf{x}}(0) e^{\omega t}$, stability means that the values of $\omega$ does not have positive real parts for all values of $k$. If $\omega$ is negative, the perturbation will decay away. If $\omega$ is imaginary, it will oscillate around the stable state. However, if it is positive and real _any_ small perturbation will grow exponentially, until a high order term of the reaction equation becomes important.

To find $\omega$, we need to solve the equation

$\hbox{Det}(R - k^{2}D - \omega I) = 0 $

Writing $J = R - k^{2}D$, this equitation takes the form

$\omega^{2} - \omega\hbox{Tr}(J) + \hbox{Det}(J) = 0$

Solving for $\omega$, we get

$\omega = \frac{1}{2}(\hbox{Tr}(J) \pm \sqrt{\hbox{Tr}(J)^{2} - 4 \hbox{Det}(J) })$

### Conditions for (in)Stability

From our initial assumption that there was a stable homogeneous state, we require that $\omega$ has negative real parts where $k = 0$, which corresponds to the spatially homogeneous solution. For this to be true, we require that

 - $\hbox{Tr}(R) < 0$
 - $\hbox{det}(R) > 0$

Or, in terms of the components of $R$:
 - $r_{aa} + r_{bb} < 0$
 - $r_{aa}r_{bb} - r_{ab}r_{ba} > 0$

For an instability to now occur at finite wavelength, we need one of the following conditions to hold:
 - $\hbox{Tr}(J) > 0$
 - $\hbox{det}(J) < 0$

Because $\hbox{Tr}(J) = \hbox{Tr}(R) - k^{2}(d_{a} + d_{b})$, the first condition cannot hold for any real $k$. This means the we require the second to hold, or, after a bit of algebra

$k^{4}d_{a}d_{b} - k^{2}(d_{a}r_{bb} + d_{b}r_{aa}) + (r_{aa}r_{bb} - r_{ab}r_{ba}) < 0$

for some real value of $k$. Once again, we need to solve a quadratic equation. To do this we note that because $k$ needs to be real, $k^{2}$ must be positive. This means that at least one root of quadratic equation in $k^{2}$ needs to be positive and real. This condition is only met when

$d_{b}r_{aa} + d_{a}r_{bb} > 2\sqrt{d_{a}d_{b}(r_{aa}r_{bb} - r_{ab}r_{ba})} > 0$

And that's it. We've derived that conditions for the diffusion-reaction equations to be stable to small perturbations.

We can write the complete requirements as

1. $r_{aa} + r_{bb} < 0$
2. $r_{aa}r_{bb} - r_{ab}r_{ba} > 0$
3. $d_{b}r_{aa} + d_{a}r_{bb} > 2\sqrt{d_{a}d_{b}(r_{aa}r_{bb} - r_{ab}r_{ba})} > 0$

### Discussion
We've waded through a lot of maths to reach this point. Let's take stock of what we can make of the conditions for instability that we have derived.

Given the diffusion coefficients are positive, from the first and third equation above, we know that $r_{aa}$ and $r_{bb}$ have to have different signs, and the component with the negative sign has to be larger. Combining this we the second equation we know that either $r_{ab}$ or $r_{ba}$ has to be negative, and the other has to be positive. This two facts show why some systems like this are called activator-inhibitor system: the presence of one component increase the production of itself - the other inhibits the production of both.

With this information, the third equation shows us that the diffusion coefficients need to be different. Specifically, the diffusion coefficient of the inhibitor has to be larger then that of the activator.

Together, this gives us a hand-waving explanation of what might be going on: Consider starting with a small increase in the activator at some point. This in turn creates an increase in the inhibitor at that point. Both of these chemical diffuse to nearby points, but the inhibitor diffuses faster, lowering the activator concentration of nearby points. This lowering of the activator concentration at nearby points, which in turn lowers the inhibitor concentration. The disturbance spreads out like a wave.

It is a lot easier to get a feel for what's going on once we visualise the this perturbation:

```python
Da, Db, alpha, beta = 1, 100, -0.005, 10

def Ra(a,b): return a - a ** 3 - b + alpha
def Rb(a,b): return (a - b) * beta

def initalise_bump(shape):
    a  = np.zeros(shape)
    if len(a.shape) == 1:
        a[int(a.shape[0] / 2)] = 0.3
    elif len(a.shape) == 2:
        a[int(a.shape[0] / 2), int(a.shape[1] / 2)] = 0.3

    return(
        a,
        np.zeros(shape)
    )

width = 100
dx = 1
dt = 0.001

OneDimensionalRDEquations(
    Da, Db, Ra, Rb,
    initialiser=initalise_bump,
    width=width, dx=dx, dt=dt,
    steps=250
).plot_time_evolution("1dRD_initial_bump.html", n_steps=150)
```

```python
HTML("1dRD_initial_bump.html")
```

<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/
css/font-awesome.min.css">

    <input id="_anim_slider9950537fb6cd4da1b9be1bc76c93b744" type="range" class="anim-slider"
           name="points" min="0" max="1" step="1" value="0"
           oninput="anim9950537fb6cd4da1b9be1bc76c93b744.set_frame(parseInt(this.value));"></input>

      <button onclick="anim9950537fb6cd4da1b9be1bc76c93b744.slower()"></button>
      <button onclick="anim9950537fb6cd4da1b9be1bc76c93b744.first_frame()">
          </button>
      <button onclick="anim9950537fb6cd4da1b9be1bc76c93b744.previous_frame()">
          </button>
      <button onclick="anim9950537fb6cd4da1b9be1bc76c93b744.reverse_animation()">
          </button>
      <button onclick="anim9950537fb6cd4da1b9be1bc76c93b744.pause_animation()">
          </button>
      <button onclick="anim9950537fb6cd4da1b9be1bc76c93b744.play_animation()">
          </button>
      <button onclick="anim9950537fb6cd4da1b9be1bc76c93b744.next_frame()">
          </button>
      <button onclick="anim9950537fb6cd4da1b9be1bc76c93b744.last_frame()">
          </button>
      <button onclick="anim9950537fb6cd4da1b9be1bc76c93b744.faster()"></button>

    <form action="#n" name="_anim_loop_select9950537fb6cd4da1b9be1bc76c93b744" class="anim-state">
      <input type="radio" name="state" value="once" id="_anim_radio1_9950537fb6cd4da1b9be1bc76c93b744"
             >
      Once
      <input type="radio" name="state" value="loop" id="_anim_radio2_9950537fb6cd4da1b9be1bc76c93b744"
             checked>
      Loop
      <input type="radio" name="state" value="reflect" id="_anim_radio3_9950537fb6cd4da1b9be1bc76c93b744"
             >
      Reflect
    </form>

### Exploring the Parameter Space

It is interesting to ask how the parameters of the equations affect the pattern formation. To get a feel for what this dependence is, we can investigate the amplitude of the instability for different frequencies. Close to equilibrium, we expect the frequency with the largest real component to dominate the dynamics of the system.

Calculating this value isn't mathematically difficult: we have an equation of the amplitude $\omega$ in terms of the frequency $k$ above. Differentiating an equation of this size by hand can become tedious due to its size, and it is easy to introduce errors. And why carry out simple replacement steps when we have a computer to hand?

In the following, I use the computer algebra system [sympy](http://www.sympy.org/en/index.html) to find the largest real mode of the system

```python
import sympy as sp

a,b,alpha,beta = sp.symbols("a,b,alpha,beta")
Raa, Rab, Rba, Rbb = sp.symbols("Raa, Rab, Rba, Rbb")
Da, Db = sp.symbols("Da, Db")
k2 = sp.Symbol("k2")
# create matricies
R = sp.Matrix(
    [[Raa, Rab],
     [Rba, Rbb]]
)

D = sp.Matrix(
    [[Da, 0],
     [0, Db]]
)

J = (R - k2 * D)
omega = sp.Matrix.trace(J) + sp.sqrt(sp.Matrix.trace(J) ** 2 - 4 * sp.Matrix.det(J))

```

```python
omega
```

$\displaystyle - Da k_{2} - Db k_{2} + Raa + Rbb + \sqrt{4 Rab Rba - 4 \left(- Da k_{2} + Raa\right) \left(- Db k_{2} + Rbb\right) + \left(- Da k_{2} - Db k_{2} + Raa + Rbb\right)^{2}}$

```python
# find the maximum value of omega for k^{2}
omega_prime = sp.diff(omega, k2)
sols = sp.solvers.solve(omega_prime, k2)
max_k2 = sols[0]

max_k2
```

$\displaystyle \frac{Da Db Raa - Da Db Rbb - Da \sqrt{- Da Db Rab Rba} - Db \sqrt{- Da Db Rab Rba}}{Da Db \left(Da - Db\right)}$

```python
def get_length_scale(al, be, da, db):

    # rewritng in terms of Da, Db, alpha, beta
    Ra = a - a**3 - b + alpha
    Rb = beta * (a - b)

    # we expand around the homogenius steady state
    zero_subs = [
        (a, sp.sign(alpha) * sp.cbrt(sp.Abs(alpha))),
        (b, sp.sign(alpha) * sp.cbrt(sp.Abs(alpha)))
    ]

    # and linearise
    R_prime_subs = {
        (Raa, sp.diff(Ra, a)),
        (Rab, sp.diff(Ra, b)),
        (Rba, sp.diff(Rb, a)),
        (Rbb, sp.diff(Rb, b))
    }

    # putting in our numeric values we get
    vals = [
        (alpha, al),
        (beta, be),
        (Da, da),
        (Db, db)
    ]

    # substitute it all in to find the maximum k
    max_k2 = [sp.N(
        sol
        .subs(R_prime_subs)
        .subs(zero_subs)
        .subs(vals)
    ) for sol in sols]

    k2 = max(sp.re(sym) for sym in max_k2)

    # if k2 is negative, no real solution exists
    if k2 <= 0:
        return -1

    # convert k2 into length units
    return sp.N(2 * sp.pi / sp.sqrt(k2))

get_length_scale(-0.005, 10, 1, 100)
```

$\displaystyle 13.6336345738685$

Which looks about right when we compare it to our simulations above - the spatial variation is about 14 length units.

Let's use it to see how the length scale of the system changes as a function of $\alpha$ and $\beta$:

```python
betas = [(1 + i) * 0.125 for i in range(0,40)]
alphas = [i * 0.05 for i in range(-20,20)]

outcomes = np.zeros((len(betas), len(alphas)))

for x,al in enumerate(alphas):
    for y,be in enumerate(betas):
        outcomes[y,x] = get_length_scale(al, be, 1, 100)

plt.figure(figsize=(8,8))

o = outcomes
o[outcomes == 0] = -1

plt.imshow(o, cmap="hsv", interpolation="none")
plt.colorbar()

plt.xticks(*zip(*[(n,l) for n,l in enumerate(alphas) if n % 5 == 0]), rotation=90)
plt.yticks(*zip(*[(n,l) for n,l in enumerate(betas) if n % 5 == 0]), rotation=0)

plt.title("Lengthscale", fontsize=20)
plt.xlabel(r"$\alpha$", fontsize=18)
plt.ylabel(r"$\beta$", fontsize=18);
```

And take a look at the long length scale we should see when we use a low value of $\beta$:

```python
Da, Db, alpha, beta = 1, 100, 0.01, 0.25

def Ra(a,b): return a - a ** 3 - b + alpha
def Rb(a,b): return (a - b) * beta

width = 200
dx = 1
dt = 0.001

TwoDimensionalRDEquations(
    Da, Db, Ra, Rb,
    width=width, height=width,
    dx=dx, dt=dt, steps=150
).plot_evolution_outcome("2dRD_small_beta.png", n_steps=100)
```

[](http://www.degeneratestate.org/static/turing-patterns/2dRD_small_beta.gif)

### Initial Conditions

Adjusting the parameters gives us control over the length scale of the system. We can also gain some control over the system by adjusting the initial conditions of the system. For example, we can impose symmetries on the system by making the initial conditions symmetric:

```python
from scipy.ndimage.interpolation import rotate

def average_rotate(a, degree):
    """
    Takes a 2d array a, and produces the average arrays,
    having rotated it degree times. The resulting shape
    has approximate degree-fold rotational symmetry.
    """
    theta = 360 / degree

    a = np.mean([rotate(a, theta * i, reshape=False) for i in range(degree)], axis=0)

    return a

def random_symmetric_initialiser(shape, degree):
    """
    Random initialiser with degree-fold symmetry.
    """

    a = np.random.normal(loc=0, scale=0.05, size=shape)
    b = np.random.normal(loc=0, scale=0.05, size=shape)

    return (
        average_rotate(a, degree),
        average_rotate(b, degree)
    )

Da, Db, alpha, beta = 1, 100, 0.01, 1

def Ra(a,b): return a - a ** 3 - b + alpha
def Rb(a,b): return (a - b) * beta

width = 200
dx = 1
dt = 0.001

# three fold
three_fold_initialiser = lambda shape: random_symmetric_initialiser(shape, 3)

TwoDimensionalRDEquations(
    Da, Db, Ra, Rb,
    initialiser=three_fold_initialiser,
    width=width, height=width,
    dx=dx, dt=dt, steps=250
).plot_evolution_outcome("2dRD_3_fold_sym.png", n_steps=150)

# five fold
five_fold_initialiser = lambda shape: random_symmetric_initialiser(shape, 5)

TwoDimensionalRDEquations(
    Da, Db, Ra, Rb,
    initialiser=five_fold_initialiser,
    width=width, height=width,
    dx=dx, dt=dt, steps=250
).plot_evolution_outcome("2dRD_5_fold_sym.png", n_steps=150)
```

Three fold rotational symmetry:

Five fold rotational symmetry:

The symmetry isn't perfect due to implementing it one a square grid, but it works quite well.

### Spatial Effects

Another interesting extension to these systems is to see what happens when we allow the parameters of the system to vary in space. In our implementation, this is just a matter of making the parameters a grid as well:

```python
Da, Db, alpha, beta = 1, 100, 0.01, 10

width = 200
dx = 1
dt = 0.001

x,y = np.mgrid[0:width,0:width]
beta = 0.1 + 5 * (1 + np.sin(2 * np.pi * y / 50)) * (1 + np.sin(2 * np.pi * x / 50))

def Ra(a,b): return a - a ** 3 - b + alpha
def Rb(a,b): return (a - b) * beta

TwoDimensionalRDEquations(
    Da, Db, Ra, Rb,
    width=width, height=width,
    dx=dx, dt=dt, steps=100
).plot_evolution_outcome("2dRD_spatial.png", n_steps=200)
```

```python
[](http://www.degeneratestate.org/static/turing-patterns/2dRD_spatial.gif)
```

## Similar Systems

Turing patterns are only one part of pattern generation from non-linear PDEs. Given we have the tools to explore these systems, it is worth looking at another simple system in which pattern formation occurs: [the Gray-Scott equations](https://groups.csail.mit.edu/mac/projects/amorphous/GrayScott/). As described in the paper [Complex Patterns in a Simple System](http://www.staff.science.uu.nl/~frank011/Classes/complexity/Literature/Pearson.pdf), for an interesting set of initial conditions the Gray-Scott equations result in a range complex patterns being formed.

While these equations _are_ reaction-diffusion equations, the patterns that end up being formed are not from Turing instabilities. Instead they come from the initial conditions of the system: a small region in the centre of the region is perturbed. As this perturbation spreads out, strange patterns are formed.

To visualise it, we just need to pass another initialisation function of our previous class, and put in new reaction equations. The parameters for the interesting systems are taken from [here](http://www.aliensaint.com/uo/java/rd/). I'm not currently aware of any theory that gives a full explanation of these patterns.

```python
def gs_initialiser(shape):
        a = np.ones(shape)
        b = np.zeros(shape)
        centre = int(shape[0] / 2)

        a[centre-20:centre+20,centre-20:centre+20] = 0.5
        b[centre-20:centre+20,centre-20:centre+20] = 0.25

        a += np.random.normal(scale=0.05, size=shape)
        b += np.random.normal(scale=0.05, size=shape)

        return a,b

# interesting parameters taken from http://www.aliensaint.com/uo/java/rd/
params = [
    [0.16, 0.08, 0.035, 0.065],
    [0.14, 0.06, 0.035, 0.065],
    [0.16, 0.08, 0.06, 0.062],
    [0.19, 0.05, 0.06, 0.062],
    [0.16, 0.08, 0.02, 0.055],
    [0.16, 0.08, 0.05, 0.065],
    [0.16, 0.08, 0.054, 0.063],
    [0.16, 0.08, 0.035, 0.06]
]

for i, param in enumerate(params):

    Da, Db, f, k = param

    def Ra(a,b): return - a*b*b + f*(1-a)
    def Rb(a,b): return + a*b*b - (f+k)*b

    width = 200
    dx = 1
    dt = 1

    TwoDimensionalRDEquations(
        Da, Db, Ra, Rb,
        initialiser=gs_initialiser,
        width=width, height=width,
        dx=dx, dt=dt, steps=200
    ).plot_evolution_outcome("gs_{}.png".format(i), n_steps=100)
```

[](http://www.degeneratestate.org/static/turing-patterns/gs_0.gif)

[](http://www.degeneratestate.org/static/turing-patterns/gs_1.gif)

[](http://www.degeneratestate.org/static/turing-patterns/gs_2.gif)

[](http://www.degeneratestate.org/static/turing-patterns/gs_3.gif)

[](http://www.degeneratestate.org/static/turing-patterns/gs_4.gif)

[](http://www.degeneratestate.org/static/turing-patterns/gs_5.gif)

[](http://www.degeneratestate.org/static/turing-patterns/gs_6.gif)

[](http://www.degeneratestate.org/static/turing-patterns/gs_7.gif)

## Conclusion

It's been interesting to play with these non-linear systems. One of the main challenges I've found with looking at them is how you find "interesting" parameters. I have some ideas about how we might search for these automatically, but that will have to wait for another post.

The complexity that can arise from these simple systems surprised me at fist, but it [has been shown](http://schulmanlab.jhu.edu/papers/reaction-diffusion-ca-journal-version.pdf) that it is possible to encode cellular automata in reaction diffusion systems. This suggests that the patterns formed by reaction-diffusion systems can be as complex as those produced by any Turing-complete system, and that any attempt to provide a quantitative explanation for their full behaviour will eventually run into some undecidable statement.

And with that connection between Turing's work on reaction-diffusion equations and his more well known work on computability, I think it's time to end this post.

## Code
This post was created from a jupyter notebook. You can find it [here](https://github.com/ijmbarr/turing-patterns).

```python
int(3.8)
```

    3

```python

```

```python

```

```python

```


# Tensor

```python
from lambeq import ccg2discocat

depccg_parser = ccg2discocat.DepCCGParser()
diagram = depccg_parser.sentence2diagram('Alice gives Claire the flowers')
diagram.draw()
```

```python
from lambeq.tensor import TensorAnsatz, MPSAnsatz, SpiderAnsatz
from lambeq.core.types import AtomicType
from discopy import Dim

N = AtomicType.NOUN
S = AtomicType.SENTENCE
```

```python
TensorAnsatz({N: Dim(4), S: Dim(3)})(diagram).draw()
```

```python
MPSAnsatz({N: Dim(4), S: Dim(3)}, bond_dim=5)(diagram).draw(figsize=(8, 4))
```

```python
SpiderAnsatz({N: Dim(4), S: Dim(3)})(diagram).draw()
```

```python
import torch as th
from sympy import default_sort_key

d = SpiderAnsatz({N: Dim(4), S: Dim(3)}, max_order=2)(diagram)

syms = sorted(d.free_symbols, key=default_sort_key)
sym_dict = {k: th.ones(k.size) for k in syms}
subbed_diagram = d.lambdify(*syms)(*sym_dict.values())
```

```python
import tensornetwork as tn
subbed_diagram.eval(contractor=tn.contractors.auto)
```

    Tensor(dom=Dim(1), cod=Dim(3), array=[256., 256., 256.])


```python
import sympy
from phasor.utilities.ipynb.displays import *
from phasor.utilities.ipynb.ipy_sympy import *
```

    Populating the interactive namespace from numpy and matplotlib
    Sympy version:  1.0

```python
Z_11 = sympy.var('Z_11')
Z_22 = sympy.var('Z_22')
Z_12 = sympy.var('Z_12')
Z_21 = sympy.var('Z_21')
Z = sympy.Matrix([[Z_11, Z_12], [Z_21, Z_22]])
Z = sympy.Matrix([[Z_11, Z_12], [Z_21, Z_22]])
Z
Y = Z**-1
Y.simplify()
Y
Y = sympy.Matrix([[0, 1/Z_11], [1/Z_11, 0]])
```

```python
B_I = sympy.Matrix([[1,0],[-1,0],[0,1],[0,-1]])
B_V = sympy.Matrix([[1,0],[1,0],[0,1],[0,1]])
B_X = sympy.Matrix([[-1,0],[1,0],[0,1],[0,1]])
B_I.transpose()
```

```python
Z4 = B_I * Z * (B_I.transpose())
Z4
Y4 = sympy.Matrix([[1/Z_11,-1/Z_11,1/Z_12,-1/Z_12],[-1/Z_11,1/Z_11,-1/Z_12,1/Z_12],[1/Z_21,-1/Z_21,1/Z_22,-1/Z_22],[-1/Z_21,1/Z_21,-1/Z_22,1/Z_22]])
Y4

```

```python
I4 = sympy.eye(4)
Z_c = sympy.var('Z_c')
Y_c = sympy.var('Y_c')
y_c = sympy.sqrt(Y_c) * I4
z_c = sympy.sqrt(Z_c) * I4
z_c = 1/sympy.sqrt(Y_c) * I4
S = ((y_c * Z4  * y_c - I4) * (y_c * Z4  * y_c + I4)**(-1))
S = (I4 - z_c * Y4  * z_c ) * (I4 + z_c * Y4  * z_c)**(-1)
S.simplify()
display(S)
```

```python
print(S[0,0] == S[1,1])
print(S[1,0] == S[0,1])
print(S[2,0] == -S[2,1])
print(S[2,0] == -S[3,0])
print(S[2,0] == S[3,1])
print(S[3,0] == S[2,1])
```

    True
    True
    True
    True
    True
    True

```python

A = sympy.var('A')
Z_11 = sympy.var('Z_11')
Z_22 = sympy.var('Z_22')
Z_12 = sympy.var('Z_12')
Z_21 = sympy.var('Z_21')
Z = sympy.Matrix([[Z_12, -Z_12], [-Z_12, Z_12]])
Y = sympy.Matrix([[1/Z_12, -1/Z_12], [-1/Z_12, 1/Z_12]])

I2 = sympy.eye(2)
Z_c = sympy.var('Z_c')
Y_c = sympy.var('Y_c')
y_c = sympy.sqrt(Y_c) * I2
z_c = sympy.sqrt(Z_c) * I2
z_c = 1/sympy.sqrt(Y_c) * I2
S = ((y_c * Z  * y_c - I2) * (y_c * Z  * y_c + I2)**(-1))
S = (I2 - z_c * Y  * z_c ) * (I2 + z_c * Y  * z_c)**(-1)
S.simplify()
display(S)
display(sympy.limit(S[0,0], A, sympy.oo))
display(sympy.limit(S[0,1], A, sympy.oo))
```

```python

```


# Números complexos

Neste notebook exploramos alguns aspectos dos números complexos. Especialmente, vamos falar da interferência entre duas ondas da mesma frequência.

Vimos nas aulas passadas que uma função cossenoidal geral, expressa por:

\begin{equation}
x(t) = \mathrm{Re}\left\{A\mathrm{e}^{-\mathrm{j}\phi} \ \mathrm{e}^{\mathrm{j}\omega t}    \right\}
\end{equation}
em que $\tilde{A} = A\mathrm{e}^{-\mathrm{j}\phi}$ é a amplitude complexa do cosseno e contêm as informações de magnitude, $A$, e fase, $\phi$. Esta amplitude complexa pode ser representada no plano complexo por:

<div>

</div>

Imagine que temos duas ondas, ***de mesma frequência***, interferindo entre si. Queremos calcular a onda resultante. Então, podemos somá-las. Se cada uma das ondas é descrita por um número complexo $z_1$ e $z_2$, do tipo:

\begin{equation}
\tilde{z}_1 = a_1 + \mathrm{j} b_1 = |\tilde{z}_1| \mathrm{e}^{\mathrm{j}\phi_1}
\end{equation}

e

\begin{equation}
\tilde{z}_2 = a_2 + \mathrm{j} b_2 = |\tilde{z}_2| \mathrm{e}^{\mathrm{j}\phi_2}
\end{equation}

Vamos fazer algumas análises a seguir

```python
# importar as bibliotecas necessárias
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 14})
```

```python
# tempo e frequência
t = np.linspace(-2, 2, 1000) # vetor temporal
freq = 1
w = 2*np.pi*freq

# onda 1
M1 = 2
phi_1 = np.deg2rad(0)
z1 = M1*np.exp(1j*phi_1)
xt1 = np.real(z1*np.exp(1j*w*t))

# onda 2
M2 = 1.2
phi_2 = np.deg2rad(0)
z2 = M2*np.exp(1j*phi_2)
xt2 = np.real(z2*np.exp(1j*w*t))
```

Temos agora 2 opções para calcular a onda resultante. A primeira é somar os sinais no domínio do tempo

\begin{equation}
x(t) = x_1(t) + x_2(t).
\end{equation}

A segunda é somar as amplitudes complexas

\begin{equation}
z = z_1 + z_2
\end{equation}
e então construir o sinal resultante $x(t) = \tilde{z}\mathrm{e}^{\mathrm{j}\omega t}$

```python
# Sinal resultante pela soma das amplitudes complexas
z = z1+z2
xt = np.real(z*np.exp(1j*w*t))

# Figura
plt.figure(figsize=(12,8))

plt.subplot(2,1,2)
plt.title('Sinal resultante')
plt.plot(t, xt, '-r', linewidth = 2, label = 'resultante')
plt.plot(t, xt1, '--b', linewidth = 1, label = r'$x_1(t)$')
plt.plot(t, xt2, '--b', linewidth = 1, label = r'$x_2(t)$')
plt.legend(loc = 'upper right')
plt.grid(linestyle = '--', which='both')
plt.xlabel('Tempo [s]')
plt.ylabel(r'$x(t)$ [-]')
plt.ylim((-2, 2))
plt.xlim((t[0], t[-1]))

plt.subplot(2,2,1)
plt.plot(t, xt1, '-b', linewidth = 2)
plt.grid(linestyle = '--', which='both')
plt.xlabel('Tempo [s]')
plt.ylabel(r'$x_1(t)$ [-]')
plt.ylim((-2, 2))
plt.xlim((t[0], t[-1]))

plt.subplot(2,2,2)
plt.plot(t, xt2, '-b', linewidth = 2)
plt.grid(linestyle = '--', which='both')
plt.xlabel('Tempo [s]')
plt.ylabel(r'$x_2(t)$ [-]')
plt.ylim((-2, 2))
plt.xlim((t[0], t[-1]))
plt.tight_layout()
plt.show()

```

```python
plt.figure(figsize=(12,4))
plt.title('Tensão, corrente e potência')
plt.plot(t, xt1, '--b', linewidth = 1, label = r'$v(t)$ [V]')
plt.plot(t, xt2, '--g', linewidth = 1, label = r'$i(t)$ [A]')
plt.plot(t, xt1*xt2, 'r', linewidth = 2, label = r'$w(t)$ [J/s]')
#plt.plot(t, np.mean(xt1*xt2)*np.ones(len(t)), '--k', linewidth = 3, label = r'$<w(t)>$ [J/s]')
plt.legend(loc = 'upper right')
plt.grid(linestyle = '--', which='both')
plt.xlabel('Tempo [s]')
plt.ylabel('Amplitude [V], [A], [J/s]')
plt.ylim((-3, 3))
plt.xlim((t[0], t[-1]))
```

```python

```

Aula 7 - Numeros complexos/Numeros complexos.ipynb


# Asymptotic small $R_s$ solution to the equation (core flow)

\begin{equation}\label{p1introhpa} \Psi _{\eta \eta \tau }  = \frac{1}{{R_s }}\Psi _{\eta \eta \eta \eta }  + \Psi _{\eta \eta \eta } \Psi _\theta   - \Psi _{\eta \eta \theta } \Psi _\eta, \\
\quad \Psi(\eta=\mp 1) = 0, \qquad \Psi_\eta(\eta=\mp 1) = - sin\theta, \qquad
-1 \le \eta \le1, \quad 0 \le \theta \le \pi
\end{equation}

The accuracy of the small R approximation decreases when the number of terms in the series are increased.
With 3 terms we can get an excellent agreement to numerical solutions for $R_s<40$ with 5 terms the agreement is good for $R_s<20$

Boundary layers do exist near $\eta$ = $\mp$ 1 (the fourth derivative of $\Psi$ is very large in this vacinity and so it is anticipated that this solution can at best approximate the inviscid core region for R values that exceed unity).

### Text form of the small $R_s$ series result
$\Psi(\theta,\eta) = -η(η - 1)(η + 1)sin(θ)/2 + \\
R_sη(η - 1)^2(η + 1)^2(η^2 + 2)sin(2θ)/560 + \\
R_s^2η(η - 1)^2(η + 1)^2(252η^6sin(θ)^2 + 168η^6 + 1659η^4sin(θ)^2 - 1204η^4 - 498η^2sin(θ)^2 - 200η^2 - 1269sin(θ)^2 + 804)sin(θ)/15523200+\\
R_s^3η(η - 1)^2(η + 1)^2(2184η^{10}cos(θ)^2 + 1540η^{10} + 24213η^8cos(θ)^2 - 44205η^8 + 18942η^6cos(θ)^2 + 33446η^6 - 101444η^4cos(θ)^2 + 66052η^4 - 23086η^2cos(θ)^2 - 6746η^2 - 14889cos(θ)^2 - 9383)sin(θ)cos(θ)/28252224000+\\
R_s^4η(η - 1)^2(η + 1)^2(968647680η^{14}sin(θ)^5 + 14774464320η^{14}sin(θ) + 3510571680η^{14}sin(3θ) - 393513120η^{14}sin(5θ) - 39671478000η^{12}sin(θ)^5 - 75537556710η^{12}sin(θ) - 28276357725η^{12}sin(3θ) - 3752563815η^{12}sin(5θ) - 181021246560η^{10}sin(θ)^5 + 357286638324η^{10}sin(θ) + 75142631718η^{10}sin(3θ) - 1180776366η^10sin(5θ) + 677920708080η^8sin(θ)^5 - 645834258762η^8sin(θ) - 123813530379η^8sin(3θ) - 1711397457η^8sin(5θ) + 193167076032η^6sin(θ)^5 - 82870720296η^6sin(θ) + 215941919508η^6sin(3θ) + 59820477948η^6sin(5θ) + 153978403824η^4sin(θ)^5 - 123221433370η^4sin(θ) + 181687022685η^4sin(3θ) - 60662329497η^4sin(5θ) - 500785425504η^2sin(θ)^5 + 367229681332η^2sin(θ) - 134582502330η^2sin(3θ) - 33288605262η^2sin(5θ) - 1507832445168sin(θ)^5 + 969877856394sin(θ) - 482955016725sin(3θ) - 9092499471sin(5θ))/16189310893916160000+\\
R_s^5η(η - 1)^2(η + 1)^2(103777390080η^{18}sin(θ)^5cos(θ) + 362623951200η^{18}sin(2θ) + 4216947840η^{18}sin(4θ) - 888844320η^{18}sin(6θ) + 1706239019520η^{16}sin(θ)^5cos(θ) - 3587535625730η^{16}sin(2θ) - 148037567160η^{16}sin(4θ) + 6928352550η^{16}sin(6θ) + 7316563474080η^{14}sin(θ)^5cos(θ) + 12700854581100η^{14}sin(2θ) + 2302804192080η^{14}sin(4θ) + 26465177340η^{14}sin(6θ) - 20744718815520η^{12}sin(θ)^5cos(θ) - 29477058481675η^{12}sin(2θ) - 7370793358740η^{12}sin(4θ) + 114145769745η^{12}sin(6θ) - 56333233167456η^{10}sin(θ)^5cos(θ) + 46778789450358η^{10}sin(2θ) + 10566022002984η^{10}sin(4θ) - 463951405890η^{10}sin(6θ) + 63153994161888η^8sin(θ)^5cos(θ) - 24308118830849η^8sin(2θ) - 14369459254332η^8sin(4θ) - 1155666816045η^8sin(6θ) + 113674430195424η^6sin(θ)^5cos(θ) - 17950415955472η^6sin(2θ) + 10835837882688η^6sin(4θ) + 2475780676656η^6sin(6θ) + 135162864362400η^4sin(θ)^5cos(θ) - 26290614787045η^4sin(2θ) + 22217682998868η^4sin(4θ) + 164703391167η^4sin(6θ) - 118926154452768η^2sin(θ)^5cos(θ) + 19833312224686η^2sin(2θ) - 6130704256440η^2sin(4θ) - 377624977002η^2sin(6θ) - 183711837174624sin(θ)^5cos(θ) + 29352246987795sin(2θ) - 15693432862284sin(4θ) - 1242061695273sin(6θ))/52129581078410035200000+...
$

```julia
using SymPy
using Calculus
import_from(sympy)
using Plots
using LaTeXStrings
pyplot()
x, η, R, θ, r = symbols("x η R θ r")

```

    (x, η, R, θ, r)

```julia
g1, g2, g3, g4, g5, g6 = symbols("g1 g2 g3 g4 g5 g6", cls=sympy.Function)
@symfuns f1 f2 f3 f4 f5 f6

#@syms t1 t2 t3 t4 t5
```

    (f1, f2, f3, f4, f5, f6)

### First term

```julia
bcs= ((f1, -1, 0),(f1,1,0),(f1',-1,-sin(θ)),(f1',1,-sin(θ)))
g1 =trigsimp(sympify(chop(split(dsolve(f1''''(η),f1(η),ics = bcs )|> string,", ")[2])))
```

$\begin{equation*}\frac{η \left(1 - η^{2}\right) \sin{\left(θ \right)}}{2}\end{equation*}$

### Second term

```julia
ψ = g1 + R*g2(η,θ) + R^2*g3(η,θ) + R^3*g4(η,θ) + R^4*g5(η,θ) + R^5*g6(η,θ)
diffeq = expand( ψ.diff(η,4) +  R*(ψ.diff(η,3)*ψ.diff(θ)-ψ.diff(η,2,θ,1)*ψ.diff(η)));
trigsimp(diffeq.coeff(R))|> string
```

    "-3*η^3*sin(2*θ)/2 + Derivative(g2(η, θ), (η, 4))"

```julia
bcs= ((f2, -1, 0),(f2,1,0),(f2',-1,0),(f2',1,0))
g2= trigsimp(sympify(chop(split(dsolve(-3*η^3*sin(2θ)/2 + f2(η).diff(η, 4),f2(η), ics = bcs) |> string,", ")[2])))
```

$\begin{equation*}\frac{η \left(η - 1\right)^{2} \left(η + 1\right)^{2} \left(η^{2} + 2\right) \sin{\left(2 θ \right)}}{560}\end{equation*}$

### Third term

```julia
ψ = g1 + R*g2 + R^2*g3(η,θ) + R^3*g4(η,θ) + R^4*g5(η,θ)+ R^5*g6(η,θ)
diffeq = expand( ψ.diff(η,4) +  R*(ψ.diff(η,3)*ψ.diff(θ)-ψ.diff(η,2,θ,1)*ψ.diff(η)));
trigsimp(diffeq.coeff(R^2)) |> string
```

    "-9*η^7*sin(θ)^3/70 - 3*η^7*sin(θ)/35 - 9*η^5*sin(θ)^3/40 + 3*η^5*sin(θ)/10 + 27*η^3*sin(θ)^3/140 - 9*η^3*sin(θ)/70 - 3*η*sin(θ)^3/280 + Derivative(g3(η, θ), (η, 4))"

```julia
bcs= ((f3, -1, 0),(f3,1,0),(f3',-1,0),(f3',1,0))
g3 = trigsimp(sympify(chop(split(dsolve(-9*η^7*sin(θ)^3/70 - 3*η^7*sin(θ)/35 - 9*η^5*sin(θ)^3/40 + 3*η^5*sin(θ)/10 + 27*η^3*sin(θ)^3/140 - 9*η^3*sin(θ)/70 - 3*η*sin(θ)^3/280 + f3(η).diff(η, 4),f3(η), ics = bcs)|> string,", ")[2])))
```

$\begin{equation*}\frac{η \left(η - 1\right)^{2} \left(η + 1\right)^{2} \left(252 η^{6} \sin^{2}{\left(θ \right)} + 168 η^{6} + 1659 η^{4} \sin^{2}{\left(θ \right)} - 1204 η^{4} - 498 η^{2} \sin^{2}{\left(θ \right)} - 200 η^{2} - 1269 \sin^{2}{\left(θ \right)} + 804\right) \sin{\left(θ \right)}}{15523200}\end{equation*}$

### Fourth term

```julia
ψ = g1 + R*g2 + R^2*g3 + R^3*g4(η,θ) + R^4*g5(η,θ)+ R^5*g6(η,θ)
diffeq = expand( (ψ.diff(η,4) +  R*(ψ.diff(η,3)*ψ.diff(θ)-ψ.diff(η,2,θ,1)*ψ.diff(η))));
trigsimp(diffeq.coeff(R^3)) |> string
```

    "-47*η^11*sin(2*θ)/30800 - 39*η^11*sin(4*θ)/123200 + 61*η^9*sin(2*θ)/5376 - 27*η^9*sin(4*θ)/17920 - 603*η^7*sin(2*θ)/39200 + 3*η^7*sin(4*θ)/3136 + 123*η^5*sin(2*θ)/22400 + 69*η^5*sin(4*θ)/44800 + 29*η^3*sin(2*θ)/323400 - 13*η^3*sin(4*θ)/17600 - 257*η*sin(2*θ)/3449600 + 257*η*sin(4*θ)/6899200 + Derivative(g4(η, θ), (η, 4))"

```julia
bcs= ((f4, -1, 0),(f4,1,0),(f4',-1,0),(f4',1,0))
g4= trigsimp(sympify(chop(split(dsolve(-47*η^11*sin(2*θ)/30800 - 39*η^11*sin(4*θ)/123200 + 61*η^9*sin(2*θ)/5376 - 27*η^9*sin(4*θ)/17920 - 603*η^7*sin(2*θ)/39200 + 3*η^7*sin(4*θ)/3136 + 123*η^5*sin(2*θ)/22400 + 69*η^5*sin(4*θ)/44800 + 29*η^3*sin(2*θ)/323400 - 13*η^3*sin(4*θ)/17600 - 257*η*sin(2*θ)/3449600 + 257*η*sin(4*θ)/6899200+ f4(η).diff(η, 4),f4(η), ics = bcs)|> string,", ")[2])))
```

$\begin{equation*}\frac{η \left(η - 1\right)^{2} \left(η + 1\right)^{2} \left(2184 η^{10} \cos^{2}{\left(θ \right)} + 1540 η^{10} + 24213 η^{8} \cos^{2}{\left(θ \right)} - 44205 η^{8} + 18942 η^{6} \cos^{2}{\left(θ \right)} + 33446 η^{6} - 101444 η^{4} \cos^{2}{\left(θ \right)} + 66052 η^{4} - 23086 η^{2} \cos^{2}{\left(θ \right)} - 6746 η^{2} - 14889 \cos^{2}{\left(θ \right)} - 9383\right) \sin{\left(θ \right)} \cos{\left(θ \right)}}{28252224000}\end{equation*}$

### Fifth term

```julia
ψ = g1 + R*g2 + R^2*g3 + R^3*g4 + R^4*g5(η,θ)+ R^5*g6(η,θ)
diffeq = expand( (ψ.diff(η,4) +  R*(ψ.diff(η,3)*ψ.diff(θ)-ψ.diff(η,2,θ,1)*ψ.diff(η))));
trigsimp(diffeq.coeff(R^4))|> string
```

    "3*η^15*sin(θ)^5/98000 + 71*η^15*sin(θ)^3/2002000 - 2819*η^15*sin(θ)/21021000 + 183*η^13*sin(θ)^5/582400 - 103*η^13*sin(θ)^3/145600 + 29*η^13*sin(θ)/36400 + 29*η^11*sin(θ)^5/2464000 + 411*η^11*sin(θ)^3/308000 - 8*η^11*sin(θ)/4125 - 79*η^9*sin(θ)^5/78400 - 317*η^9*sin(θ)^3/235200 + η^9*sin(θ)/400 + 10357*η^7*sin(θ)^5/60368000 + 1791*η^7*sin(θ)^3/1078000 - 12893*η^7*sin(θ)/7546000 + 7947*η^5*sin(θ)^5/17248000 - 591*η^5*sin(θ)^3/616000 + 199*η^5*sin(θ)/404250 - 85517*η^3*sin(θ)^5/941740800 + 55859*η^3*sin(θ)^3/588588000 - 37*η^3*sin(θ)/1681680 + 67*η*sin(θ)^5/22422400 - 67*η*sin(θ)^3/47087040 + Derivative(g5(η, θ), (η, 4))"

```julia
bcs= ((f5, -1, 0),(f5,1,0),(f5',-1,0),(f5',1,0))
g5=  trigsimp(sympify(chop(split(dsolve( 3*η^15*sin(θ)^5/98000 + 71*η^15*sin(θ)^3/2002000 - 2819*η^15*sin(θ)/21021000 + 183*η^13*sin(θ)^5/582400 - 103*η^13*sin(θ)^3/145600 + 29*η^13*sin(θ)/36400 + 29*η^11*sin(θ)^5/2464000 + 411*η^11*sin(θ)^3/308000 - 8*η^11*sin(θ)/4125 - 79*η^9*sin(θ)^5/78400 - 317*η^9*sin(θ)^3/235200 + η^9*sin(θ)/400 + 10357*η^7*sin(θ)^5/60368000 + 1791*η^7*sin(θ)^3/1078000 - 12893*η^7*sin(θ)/7546000 + 7947*η^5*sin(θ)^5/17248000 - 591*η^5*sin(θ)^3/616000 + 199*η^5*sin(θ)/404250 - 85517*η^3*sin(θ)^5/941740800 + 55859*η^3*sin(θ)^3/588588000 - 37*η^3*sin(θ)/1681680 + 67*η*sin(θ)^5/22422400 - 67*η*sin(θ)^3/47087040 + f5(η).diff(η, 4),f5(η), ics = bcs)|> string,", ")[2])))
```

$\begin{equation*}\frac{η \left(η - 1\right)^{2} \left(η + 1\right)^{2} \left(- 166486320 η^{14} \sin^{4}{\left(θ \right)} - 192875760 η^{14} \sin^{2}{\left(θ \right)} + 729331680 η^{14} - 3116015595 η^{12} \sin^{4}{\left(θ \right)} + 5879897100 η^{12} \sin^{2}{\left(θ \right)} - 5597795280 η^{12} - 6247302138 η^{10} \sin^{4}{\left(θ \right)} - 8654843736 η^{10} \sin^{2}{\left(θ \right)} + 18025332864 η^{10} + 20329323399 η^{8} \sin^{4}{\left(θ \right)} + 16546314708 η^{8} \sin^{2}{\left(θ \right)} - 32057244912 η^{8} + 35946710100 η^{6} \sin^{4}{\left(θ \right)} - 64380538656 η^{6} \sin^{2}{\left(θ \right)} + 27001794624 η^{6} - 25519339629 η^{4} \sin^{4}{\left(θ \right)} + 15203078100 η^{4} \sin^{2}{\left(θ \right)} + 3703999600 η^{4} - 32293847178 η^{2} \sin^{4}{\left(θ \right)} + 37628191080 η^{2} \sin^{2}{\left(θ \right)} - 6342526624 η^{2} - 51666013647 \sin^{4}{\left(θ \right)} + 66052189260 \sin^{2}{\left(θ \right)} - 16389052848\right) \sin{\left(θ \right)}}{505915965434880000}\end{equation*}$

### Sixth term

```julia
ψ = g1 + R*g2 + R^2*g3 + R^3*g4 + R^4*g5+ R^5*g6(η,θ)
diffeq = expand( (ψ.diff(η,4) +  R*(ψ.diff(η,3)*ψ.diff(θ)-ψ.diff(η,2,θ,1)*ψ.diff(η))));
trigsimp(diffeq.coeff(R^5))|> string
```

    "-419*η^19*(1 - cos(2*θ))^2*sin(2*θ)/44568832000 - 3*η^19*(cos(2*θ) + 1)^2*sin(2*θ)/68992000 - 3083537*η^19*sin(2*θ)/2085821337600 + 8663*η^19*sin(4*θ)/124156032000 + η^19*sin(6*θ)/275968000 - 11691*η^17*(1 - cos(2*θ))^2*sin(2*θ)/48791142400 - 81*η^17*(cos(2*θ) + 1)^2*sin(2*θ)/292864000 + 4969847*η^17*sin(2*θ)/418209792000 + 240127*η^17*sin(4*θ)/243955712000 - 1377*η^17*sin(6*θ)/57401344000 - 904199*η^15*(1 - cos(2*θ))^2*sin(2*θ)/753392640000 + 1109*η^15*(cos(2*θ) + 1)^2*sin(2*θ)/3622080000 - 2915243*η^15*sin(2*θ)/80720640000 - 247561*η^15*sin(4*θ)/47087040000 - 101*η^15*sin(6*θ)/4829440000 + 39359*η^13*(1 - cos(2*θ))^2*sin(2*θ)/10762752000 + 4111*η^13*(cos(2*θ) + 1)^2*sin(2*θ)/4305100800 + 167151*η^13*sin(2*θ)/2609152000 + 244859*η^13*sin(4*θ)/21525504000 - 2143*η^13*sin(6*θ)/28700672000 + 874781*η^11*(1 - cos(2*θ))^2*sin(2*θ)/637486080000 - 7543*η^11*(cos(2*θ) + 1)^2*sin(2*θ)/9658880000 - 284680117*η^11*sin(2*θ)/3824916480000 - 18301*η^11*sin(4*θ)/1159065600 + 3233*η^11*sin(6*θ)/7727104000 - 16603*η^9*(1 - cos(2*θ))^2*sin(2*θ)/3161088000 - 6541*η^9*(cos(2*θ) + 1)^2*sin(2*θ)/5795328000 + 3373037*η^9*sin(2*θ)/69543936000 + 284609*η^9*sin(4*θ)/17385984000 + 289*η^9*sin(6*θ)/7727104000 - 35337*η^7*(1 - cos(2*θ))^2*sin(2*θ)/351583232000 + 265621*η^7*(cos(2*θ) + 1)^2*sin(2*θ)/188348160000 - 20683799*η^7*sin(2*θ)/1757916160000 - 4587447*η^7*sin(4*θ)/439479040000 - 494839*η^7*sin(6*θ)/753392640000 + 88313*η^5*(1 - cos(2*θ))^2*sin(2*θ)/125565440000 - 123759*η^5*(cos(2*θ) + 1)^2*sin(2*θ)/251130880000 + 513883*η^5*sin(2*θ)/602714112000 + 448897*η^5*sin(4*θ)/251130880000 + 26637*η^5*sin(6*θ)/77271040000 + 9498448951*η^3*(1 - cos(2*θ))^2*sin(2*θ)/18737628349440000 + 1649*η^3*(cos(2*θ) + 1)^2*sin(2*θ)/34245120000 - 296000683931*η^3*sin(2*θ)/337277310289920000 + 15286954247*η^3*sin(4*θ)/28106442524160000 - 409*η^3*sin(6*θ)/14350336000 - 717487647*η*(1 - cos(2*θ))^2*sin(2*θ)/12491752232960000 + 4469*η*(cos(2*θ) + 1)^2*sin(2*θ)/1506785280000 + 12631122239*η*sin(2*θ)/149901026795520000 - 368573593*η*sin(4*θ)/7495051339776000 + 4469*η*sin(6*θ)/6027141120000 + Derivative(g6(η, θ), (η, 4))"

```julia
bcs= ((f6, -1, 0),(f6,1,0),(f6',-1,0),(f6',1,0))
g6=  trigsimp(sympify(chop(split(dsolve( -419*η^19*(1 - cos(2*θ))^2*sin(2*θ)/44568832000 - 3*η^19*(cos(2*θ) + 1)^2*sin(2*θ)/68992000 - 3083537*η^19*sin(2*θ)/2085821337600 + 8663*η^19*sin(4*θ)/124156032000 + η^19*sin(6*θ)/275968000 - 11691*η^17*(1 - cos(2*θ))^2*sin(2*θ)/48791142400 - 81*η^17*(cos(2*θ) + 1)^2*sin(2*θ)/292864000 + 4969847*η^17*sin(2*θ)/418209792000 + 240127*η^17*sin(4*θ)/243955712000 - 1377*η^17*sin(6*θ)/57401344000 - 904199*η^15*(1 - cos(2*θ))^2*sin(2*θ)/753392640000 + 1109*η^15*(cos(2*θ) + 1)^2*sin(2*θ)/3622080000 - 2915243*η^15*sin(2*θ)/80720640000 - 247561*η^15*sin(4*θ)/47087040000 - 101*η^15*sin(6*θ)/4829440000 + 39359*η^13*(1 - cos(2*θ))^2*sin(2*θ)/10762752000 + 4111*η^13*(cos(2*θ) + 1)^2*sin(2*θ)/4305100800 + 167151*η^13*sin(2*θ)/2609152000 + 244859*η^13*sin(4*θ)/21525504000 - 2143*η^13*sin(6*θ)/28700672000 + 874781*η^11*(1 - cos(2*θ))^2*sin(2*θ)/637486080000 - 7543*η^11*(cos(2*θ) + 1)^2*sin(2*θ)/9658880000 - 284680117*η^11*sin(2*θ)/3824916480000 - 18301*η^11*sin(4*θ)/1159065600 + 3233*η^11*sin(6*θ)/7727104000 - 16603*η^9*(1 - cos(2*θ))^2*sin(2*θ)/3161088000 - 6541*η^9*(cos(2*θ) + 1)^2*sin(2*θ)/5795328000 + 3373037*η^9*sin(2*θ)/69543936000 + 284609*η^9*sin(4*θ)/17385984000 + 289*η^9*sin(6*θ)/7727104000 - 35337*η^7*(1 - cos(2*θ))^2*sin(2*θ)/351583232000 + 265621*η^7*(cos(2*θ) + 1)^2*sin(2*θ)/188348160000 - 20683799*η^7*sin(2*θ)/1757916160000 - 4587447*η^7*sin(4*θ)/439479040000 - 494839*η^7*sin(6*θ)/753392640000 + 88313*η^5*(1 - cos(2*θ))^2*sin(2*θ)/125565440000 - 123759*η^5*(cos(2*θ) + 1)^2*sin(2*θ)/251130880000 + 513883*η^5*sin(2*θ)/602714112000 + 448897*η^5*sin(4*θ)/251130880000 + 26637*η^5*sin(6*θ)/77271040000 + 9498448951*η^3*(1 - cos(2*θ))^2*sin(2*θ)/18737628349440000 + 1649*η^3*(cos(2*θ) + 1)^2*sin(2*θ)/34245120000 - 296000683931*η^3*sin(2*θ)/337277310289920000 + 15286954247*η^3*sin(4*θ)/28106442524160000 - 409*η^3*sin(6*θ)/14350336000 - 717487647*η*(1 - cos(2*θ))^2*sin(2*θ)/12491752232960000 + 4469*η*(cos(2*θ) + 1)^2*sin(2*θ)/1506785280000 + 12631122239*η*sin(2*θ)/149901026795520000 - 368573593*η*sin(4*θ)/7495051339776000 + 4469*η*sin(6*θ)/6027141120000 + f6(η).diff(η, 4),f6(η), ics = bcs)|> string,", ")[2])))
```

$\begin{equation*}\frac{η \left(η - 1\right)^{2} \left(η + 1\right)^{2} \left(12972173760 η^{18} \left(1 - \cos{\left(2 θ \right)}\right)^{2} \sin{\left(2 θ \right)} + 362623951200 η^{18} \sin{\left(2 θ \right)} + 4216947840 η^{18} \sin{\left(4 θ \right)} - 888844320 η^{18} \sin{\left(6 θ \right)} + 213279877440 η^{16} \left(1 - \cos{\left(2 θ \right)}\right)^{2} \sin{\left(2 θ \right)} - 3587535625730 η^{16} \sin{\left(2 θ \right)} - 148037567160 η^{16} \sin{\left(4 θ \right)} + 6928352550 η^{16} \sin{\left(6 θ \right)} + 914570434260 η^{14} \left(1 - \cos{\left(2 θ \right)}\right)^{2} \sin{\left(2 θ \right)} + 12700854581100 η^{14} \sin{\left(2 θ \right)} + 2302804192080 η^{14} \sin{\left(4 θ \right)} + 26465177340 η^{14} \sin{\left(6 θ \right)} - 2593089851940 η^{12} \left(1 - \cos{\left(2 θ \right)}\right)^{2} \sin{\left(2 θ \right)} - 29477058481675 η^{12} \sin{\left(2 θ \right)} - 7370793358740 η^{12} \sin{\left(4 θ \right)} + 114145769745 η^{12} \sin{\left(6 θ \right)} - 7041654145932 η^{10} \left(1 - \cos{\left(2 θ \right)}\right)^{2} \sin{\left(2 θ \right)} + 46778789450358 η^{10} \sin{\left(2 θ \right)} + 10566022002984 η^{10} \sin{\left(4 θ \right)} - 463951405890 η^{10} \sin{\left(6 θ \right)} + 7894249270236 η^{8} \left(1 - \cos{\left(2 θ \right)}\right)^{2} \sin{\left(2 θ \right)} - 24308118830849 η^{8} \sin{\left(2 θ \right)} - 14369459254332 η^{8} \sin{\left(4 θ \right)} - 1155666816045 η^{8} \sin{\left(6 θ \right)} + 14209303774428 η^{6} \left(1 - \cos{\left(2 θ \right)}\right)^{2} \sin{\left(2 θ \right)} - 17950415955472 η^{6} \sin{\left(2 θ \right)} + 10835837882688 η^{6} \sin{\left(4 θ \right)} + 2475780676656 η^{6} \sin{\left(6 θ \right)} + 16895358045300 η^{4} \left(1 - \cos{\left(2 θ \right)}\right)^{2} \sin{\left(2 θ \right)} - 26290614787045 η^{4} \sin{\left(2 θ \right)} + 22217682998868 η^{4} \sin{\left(4 θ \right)} + 164703391167 η^{4} \sin{\left(6 θ \right)} - 14865769306596 η^{2} \left(1 - \cos{\left(2 θ \right)}\right)^{2} \sin{\left(2 θ \right)} + 19833312224686 η^{2} \sin{\left(2 θ \right)} - 6130704256440 η^{2} \sin{\left(4 θ \right)} - 377624977002 η^{2} \sin{\left(6 θ \right)} - 22963979646828 \left(1 - \cos{\left(2 θ \right)}\right)^{2} \sin{\left(2 θ \right)} + 29352246987795 \sin{\left(2 θ \right)} - 15693432862284 \sin{\left(4 θ \right)} - 1242061695273 \sin{\left(6 θ \right)}\right)}{52129581078410035200000}\end{equation*}$

```julia
ψ6 = g1 + R*g2 + R^2*g3 + R^3*g4 + R^4*g5 + R^5*g6
ψ5 = g1 + R*g2 + R^2*g3 + R^3*g4 + R^4*g5
ψ4 = g1 + R*g2 + R^2*g3 + R^3*g4
ψ3=  g1 + R*g2 + R^2*g3
```

$\begin{equation*}\frac{R^{2} η \left(η - 1\right)^{2} \left(η + 1\right)^{2} \left(252 η^{6} \sin^{2}{\left(θ \right)} + 168 η^{6} + 1659 η^{4} \sin^{2}{\left(θ \right)} - 1204 η^{4} - 498 η^{2} \sin^{2}{\left(θ \right)} - 200 η^{2} - 1269 \sin^{2}{\left(θ \right)} + 804\right) \sin{\left(θ \right)}}{15523200} + \frac{R η \left(η - 1\right)^{2} \left(η + 1\right)^{2} \left(η^{2} + 2\right) \sin{\left(2 θ \right)}}{560} + \frac{η \left(1 - η^{2}\right) \sin{\left(θ \right)}}{2}\end{equation*}$

```julia
Reynolds=30.0
η_value = 0.6
plot(x->ψ3.subs([(θ, x), (R, Reynolds), (η, η_value)]),0,pi,label="3 terms in series",linewidth=2)
plot!(x->ψ4.subs([(θ, x), (R, Reynolds), (η, η_value)]),0,pi, linecolor=:red, linestyle=:dash, linewidth=2, label="4 terms in series")
plot!(x->ψ5.subs([(θ, x), (R, Reynolds), (η, η_value)]),0,pi, linestyle=:dot,linewidth=3, label="5 terms in series")
plot!(x->ψ6.subs([(θ, x), (R, Reynolds), (η, η_value)]),0,pi, linestyle=:dot,linewidth=3, label="6 terms in series")
xticks!(([0:π/6:π;], ["0", "\\pi/6", "\\pi/3", "\\pi/2", "2\\pi/3", "5\\pi/6","\\pi"]))
plot!(title= "Asymptotic series at "*L"\eta=%$η_value, \quad R_s= %$Reynolds",size=(1100,500), legend=:outertopright, xlabel =L"η", ylabel=L"Ψ", yguidefontrotation=-90)
```

```julia
Rmax=90
η_value = 0.6
θ_value = pi/3
xvals=0:Rmax
yvals= ones(Rmax+1)*abs(g1(θ_value,η_value))
plot(xvals, yvals, label="Term 1")
plot!(x->x*abs(g2.subs([(θ, θ_value), (η, η_value)])),0,Rmax, label="Term 2")
plot!(x->x^2*abs(g3.subs([(θ, θ_value), (η, η_value)])),0,Rmax, label="Term 3")
plot!(x->x^3*abs(g4.subs([(θ, θ_value), (η, η_value)])),0,Rmax, label="Term 4")
plot!(x->x^4*abs(g5.subs([(θ, θ_value), (η, η_value)])),0,Rmax, linestyle=:dash,label="Term 5")
plot!(x->x^5*abs(g6.subs([(θ, θ_value), (η, η_value)])),0,Rmax, linestyle=:dash,label="Term 6")
plot!(title= "Asymptotic series growth at location "*L"\eta=%$η_value"*" and "*L"\theta=%$(round(θ_value;digits=2))",size=(900,500), legend=:topleft, xlabel =L"R_s", ylabel=L"|Ψ|", yguidefontrotation=-90)
```

#### A static text backup of the smalll R series terms

```julia
#g1 = factor(-η^3*sin(θ)/2 + η*sin(θ)/2)
#g2= factor(η^7*sin(2*θ)/560 - 3*η^3*sin(2*θ)/560 + η*sin(2*θ)/280)
#g3=factor(η^11*(3*sin(θ)^2 + 2)*sin(θ)/184800 + η^9*(3*sin(θ)^2 - 4)*sin(θ)/40320 + 3*η^7*(2 - 3*sin(θ)^2)*sin(θ)/39200 + η^5*sin(θ)^3/11200 + η^3*(17*sin(θ)^3/129360 - 113*sin(θ)/970200) + η*(-141*sin(θ)^3/1724800 + 67*sin(θ)/1293600))
#g4=trigsimp(factor( η^15*(39*cos(2*θ) + 94)*sin(2*θ)/2018016000 + η^13*(81*cos(2*θ) - 305)*sin(2*θ)/461260800 + η^11*(201 - 25*cos(2*θ))*sin(2*θ)/103488000 + η^9*(23*sin(θ)^2 - 32)*sin(2*θ)/11289600 + η^7*(1911*cos(2*θ) - 116)*sin(2*θ)/1086624000 + 257*η^5*sin(θ)^3*cos(θ)/103488000 + η^3*(-257*sin(θ)^3*cos(θ)/51744000 - 23*sin(θ)^2*sin(2*θ)/2822400 - 943*sin(2*θ)*cos(2*θ)/179379200 + 24289*sin(2*θ)/4346496000) + η*(257*sin(θ)^3*cos(θ)/103488000 + 23*sin(θ)^2*sin(2*θ)/3763200 + 6359*sin(2*θ)*cos(2*θ)/1793792000 - 449161*sin(2*θ)/113008896000) ))
#g5=factor(trigsimp(η^19*(3744*sin(θ)^5 + 57106*sin(θ) + 13569*sin(3*θ) - 1521*sin(5*θ))/62574640128000 + η^17*(-2736*sin(θ)^5 - 6910*sin(θ) - 2321*sin(3*θ) - 195*sin(5*θ))/1064534016000 + η^15*(-10545*sin(θ)^5 + 54776*sin(θ) + 14157*sin(3*θ) + 621*sin(5*θ))/1695133440000 + η^13*(31920*sin(θ)^5 - 45822*sin(θ) - 9649*sin(3*θ) - 99*sin(5*θ))/516612096000 + η^11*(-317464*sin(θ)^5 + 370006*sin(θ) + 127277*sin(3*θ) + 14663*sin(5*θ))/3824916480000 + η^9*(137808*sin(θ)^5 - 186598*sin(θ) - 115677*sin(3*θ) - 56295*sin(5*θ))/5007163392000 + η^7*(-601580*sin(θ)^5 + 518734*sin(θ) - 275603*sin(3*θ) + 144495*sin(5*θ))/15821245440000 + η^5*(-393456*sin(θ)^5 + 125310*sin(θ) - 35855*sin(3*θ) - 3549*sin(5*θ))/18081423360000 + η^3*(311865013*sin(θ)^5/2007603037440000 - 49141438483*sin(θ)/505915965434880000 + 384873857*sin(3*θ)/7495051339776000 - 1907021*sin(5*θ)/2044104910848000) + η*(-1495865521*sin(θ)^5/16060824299520000 + 53882103133*sin(θ)/899406160773120000 - 2146466741*sin(3*θ)/71952492861849600 - 91843429*sin(5*θ)/163528392867840000)))
#g6=trigsimp(η*(η - 1)^2*(η + 1)^2*(12972173760*η^18*(1 - cos(2*θ))^2*sin(2*θ) + 362623951200*η^18*sin(2*θ) + 4216947840*η^18*sin(4*θ) - 888844320*η^18*sin(6*θ) + 213279877440*η^16*(1 - cos(2*θ))^2*sin(2*θ) - 3587535625730*η^16*sin(2*θ) - 148037567160*η^16*sin(4*θ) + 6928352550*η^16*sin(6*θ) + 914570434260*η^14*(1 - cos(2*θ))^2*sin(2*θ) + 12700854581100*η^14*sin(2*θ) + 2302804192080*η^14*sin(4*θ) + 26465177340*η^14*sin(6*θ) - 2593089851940*η^12*(1 - cos(2*θ))^2*sin(2*θ) - 29477058481675*η^12*sin(2*θ) - 7370793358740*η^12*sin(4*θ) + 114145769745*η^12*sin(6*θ) - 7041654145932*η^10*(1 - cos(2*θ))^2*sin(2*θ) + 46778789450358*η^10*sin(2*θ) + 10566022002984*η^10*sin(4*θ) - 463951405890*η^10*sin(6*θ) + 7894249270236*η^8*(1 - cos(2*θ))^2*sin(2*θ) - 24308118830849*η^8*sin(2*θ) - 14369459254332*η^8*sin(4*θ) - 1155666816045*η^8*sin(6*θ) + 14209303774428*η^6*(1 - cos(2*θ))^2*sin(2*θ) - 17950415955472*η^6*sin(2*θ) + 10835837882688*η^6*sin(4*θ) + 2475780676656*η^6*sin(6*θ) + 16895358045300*η^4*(1 - cos(2*θ))^2*sin(2*θ) - 26290614787045*η^4*sin(2*θ) + 22217682998868*η^4*sin(4*θ) + 164703391167*η^4*sin(6*θ) - 14865769306596*η^2*(1 - cos(2*θ))^2*sin(2*θ) + 19833312224686*η^2*sin(2*θ) - 6130704256440*η^2*sin(4*θ) - 377624977002*η^2*sin(6*θ) - 22963979646828*(1 - cos(2*θ))^2*sin(2*θ) + 29352246987795*sin(2*θ) - 15693432862284*sin(4*θ) - 1242061695273*sin(6*θ))/52129581078410035200000)|> string
```

```julia
d=1
factor(trigsimp(g1.diff(η,2,θ,d)+r*g2.diff(η,2,θ,d)+r^2*g3.diff(η,2,θ,d)))|> string
```

    "η*(3465*r^2*η^8*sin(θ)^2*cos(θ) + 770*r^2*η^8*cos(θ) + 10395*r^2*η^6*sin(θ)^2*cos(θ) - 4620*r^2*η^6*cos(θ) - 18711*r^2*η^4*sin(θ)^2*cos(θ) + 4158*r^2*η^4*cos(θ) + 3465*r^2*η^2*sin(θ)^2*cos(θ) + 1530*r^2*sin(θ)^2*cos(θ) - 452*r^2*cos(θ) + 97020*r*η^4*cos(2*θ) - 41580*r*cos(2*θ) - 1940400*cos(θ))/646800"

### The final small R asymptotic series
$\Psi(\theta,\eta) = -η(η - 1)(η + 1)sin(θ)/2 + \\
Rη(η - 1)^2(η + 1)^2(η^2 + 2)sin(2θ)/560 + \\
R^2η(η - 1)^2(η + 1)^2(252η^6sin(θ)^2 + 168η^6 + 1659η^4sin(θ)^2 - 1204η^4 - 498η^2sin(θ)^2 - 200η^2 - 1269sin(θ)^2 + 804)sin(θ)/15523200+\\
R^3η(η - 1)^2(η + 1)^2(2184η^{10}cos(θ)^2 + 1540η^{10} + 24213η^8cos(θ)^2 - 44205η^8 + 18942η^6cos(θ)^2 + 33446η^6 - 101444η^4cos(θ)^2 + 66052η^4 - 23086η^2cos(θ)^2 - 6746η^2 - 14889cos(θ)^2 - 9383)sin(θ)cos(θ)/28252224000+\\
R^4η(η - 1)^2(η + 1)^2(968647680η^{14}sin(θ)^5 + 14774464320η^{14}sin(θ) + 3510571680η^{14}sin(3θ) - 393513120η^{14}sin(5θ) - 39671478000η^{12}sin(θ)^5 - 75537556710η^{12}sin(θ) - 28276357725η^{12}sin(3θ) - 3752563815η^{12}sin(5θ) - 181021246560η^{10}sin(θ)^5 + 357286638324η^{10}sin(θ) + 75142631718η^{10}sin(3θ) - 1180776366η^10sin(5θ) + 677920708080η^8sin(θ)^5 - 645834258762η^8sin(θ) - 123813530379η^8sin(3θ) - 1711397457η^8sin(5θ) + 193167076032η^6sin(θ)^5 - 82870720296η^6sin(θ) + 215941919508η^6sin(3θ) + 59820477948η^6sin(5θ) + 153978403824η^4sin(θ)^5 - 123221433370η^4sin(θ) + 181687022685η^4sin(3θ) - 60662329497η^4sin(5θ) - 500785425504η^2sin(θ)^5 + 367229681332η^2sin(θ) - 134582502330η^2sin(3θ) - 33288605262η^2sin(5θ) - 1507832445168sin(θ)^5 + 969877856394sin(θ) - 482955016725sin(3θ) - 9092499471sin(5θ))/16189310893916160000+\\
R^5η(η - 1)^2(η + 1)^2(103777390080η^{18}sin(θ)^5cos(θ) + 362623951200η^{18}sin(2θ) + 4216947840η^{18}sin(4θ) - 888844320η^{18}sin(6θ) + 1706239019520η^{16}sin(θ)^5cos(θ) - 3587535625730η^{16}sin(2θ) - 148037567160η^{16}sin(4θ) + 6928352550η^{16}sin(6θ) + 7316563474080η^{14}sin(θ)^5cos(θ) + 12700854581100η^{14}sin(2θ) + 2302804192080η^{14}sin(4θ) + 26465177340η^{14}sin(6θ) - 20744718815520η^{12}sin(θ)^5cos(θ) - 29477058481675η^{12}sin(2θ) - 7370793358740η^{12}sin(4θ) + 114145769745η^{12}sin(6θ) - 56333233167456η^{10}sin(θ)^5cos(θ) + 46778789450358η^{10}sin(2θ) + 10566022002984η^{10}sin(4θ) - 463951405890η^{10}sin(6θ) + 63153994161888η^8sin(θ)^5cos(θ) - 24308118830849η^8sin(2θ) - 14369459254332η^8sin(4θ) - 1155666816045η^8sin(6θ) + 113674430195424η^6sin(θ)^5cos(θ) - 17950415955472η^6sin(2θ) + 10835837882688η^6sin(4θ) + 2475780676656η^6sin(6θ) + 135162864362400η^4sin(θ)^5cos(θ) - 26290614787045η^4sin(2θ) + 22217682998868η^4sin(4θ) + 164703391167η^4sin(6θ) - 118926154452768η^2sin(θ)^5cos(θ) + 19833312224686η^2sin(2θ) - 6130704256440η^2sin(4θ) - 377624977002η^2sin(6θ) - 183711837174624sin(θ)^5cos(θ) + 29352246987795sin(2θ) - 15693432862284sin(4θ) - 1242061695273sin(6θ))/52129581078410035200000+...
$

# Asymptotic small $R_s$ solution to the equation (core flow)

\begin{equation}\label{p1introhpa} \Psi _{\eta \eta \tau }  = \frac{1}{{R_s }}\Psi _{\eta \eta \eta \eta }  + \Psi _{\eta \eta \eta } \Psi _\theta   - \Psi _{\eta \eta \theta } \Psi _\eta + \epsilon \Psi _{\eta \eta \theta \theta },  \\
\quad \Psi(\eta=\mp 1) = 0, \qquad \Psi_\eta(\eta=\mp 1) = - sin\theta, \qquad
-1 \le \eta \le1, \quad 0 \le \theta \le \pi
\end{equation}

```julia
h1, h2, h3, h4, h5, h6 = symbols("h1 h2 h3 h4 h5 h6", cls=sympy.Function)
@symfuns i1 i2 i3 i4 i5 i6
ϵ = symbols("ϵ");
```

## First term

```julia
bcs= ((i1, -1, 0),(i1,1,0),(i1',-1,-sin(θ)),(i1',1,-sin(θ)))
h1 =trigsimp(sympify(chop(split(dsolve(i1''''(η),i1(η),ics = bcs )|> string,", ")[2])))
```

$\begin{equation*}\frac{η \left(1 - η^{2}\right) \sin{\left(θ \right)}}{2}\end{equation*}$

## Second term

```julia
ψ_d = h1 + R*h2(η,θ) + R^2*h3(η,θ) + R^3*h4(η,θ) + R^4*h5(η,θ)
diffeq = expand( ψ_d.diff(η,4) +  R*(ψ_d.diff(η,3)*ψ_d.diff(θ)-ψ_d.diff(η,2,θ,1)*ψ_d.diff(η) + ϵ*ψ_d.diff(η,2,θ,2)));
trigsimp(diffeq.coeff(R))|> string
```

    "-3*η^3*sin(2*θ)/2 + 3*η*ϵ*sin(θ) + Derivative(h2(η, θ), (η, 4))"

```julia
bcs= ((i2, -1, 0),(i2,1,0),(i2',-1,0),(i2',1,0))
h2= trigsimp(sympify(chop(split(dsolve(-3*η^3*sin(2θ)/2 + 3*η*ϵ*sin(θ)+ i2(η).diff(η, 4),i2(η), ics = bcs) |> string,", ")[2])))
```

$\begin{equation*}\frac{η \left(η - 1\right)^{2} \left(η + 1\right)^{2} \left(η^{2} \cos{\left(θ \right)} - 7 ϵ + 2 \cos{\left(θ \right)}\right) \sin{\left(θ \right)}}{280}\end{equation*}$

## Third term

```julia
ψ_d = h1 + R*h2 + R^2*h3(η,θ) + R^3*h4(η,θ) + R^4*h5(η,θ)
diffeq = expand( ψ_d.diff(η,4) +  R*(ψ_d.diff(η,3)*ψ_d.diff(θ)-ψ_d.diff(η,2,θ,1)*ψ_d.diff(η)+ϵ*ψ_d.diff(η,2,θ,2) ));
trigsimp(diffeq.coeff(R^2)) |> string
```

    "-9*η^7*sin(θ)^3/70 - 3*η^7*sin(θ)/35 - 9*η^5*ϵ*sin(θ)*cos(θ)/10 - 9*η^5*sin(θ)^3/40 + 3*η^5*sin(θ)/10 + η^3*ϵ^2*sin(θ)/2 + η^3*ϵ*sin(θ)*cos(θ)/10 + 27*η^3*sin(θ)^3/140 - 9*η^3*sin(θ)/70 - 3*η*ϵ^2*sin(θ)/10 + 9*η*ϵ*sin(θ)*cos(θ)/35 - 3*η*sin(θ)^3/280 + Derivative(h3(η, θ), (η, 4))"

```julia
bcs= ((i3, -1, 0),(i3,1,0),(i3',-1,0),(i3',1,0))
h3 = trigsimp(sympify(chop(split(dsolve( -9*η^7*sin(θ)^3/70 - 3*η^7*sin(θ)/35 - 9*η^5*ϵ*sin(θ)*cos(θ)/10 - 9*η^5*sin(θ)^3/40 + 3*η^5*sin(θ)/10 + η^3*ϵ^2*sin(θ)/2 + η^3*ϵ*sin(θ)*cos(θ)/10 + 27*η^3*sin(θ)^3/140 - 9*η^3*sin(θ)/70 - 3*η*ϵ^2*sin(θ)/10 + 9*η*ϵ*sin(θ)*cos(θ)/35 - 3*η*sin(θ)^3/280+i3(η).diff(η, 4),i3(η), ics = bcs)|> string,", ")[2])))
```

$\begin{equation*}\frac{η \left(η - 1\right)^{2} \left(η + 1\right)^{2} \left(252 η^{6} \sin^{2}{\left(θ \right)} + 168 η^{6} + 4620 η^{4} ϵ \cos{\left(θ \right)} + 1659 η^{4} \sin^{2}{\left(θ \right)} - 1204 η^{4} - 9240 η^{2} ϵ^{2} + 7392 η^{2} ϵ \cos{\left(θ \right)} - 498 η^{2} \sin^{2}{\left(θ \right)} - 200 η^{2} + 20328 ϵ^{2} - 23100 ϵ \cos{\left(θ \right)} - 1269 \sin^{2}{\left(θ \right)} + 804\right) \sin{\left(θ \right)}}{15523200}\end{equation*}$

## Fourth term

```julia
ψ_d = h1 + R*h2 + R^2*h3 + R^3*h4(η,θ) + R^4*h5(η,θ)
diffeq = expand( ψ_d.diff(η,4) +  R*(ψ_d.diff(η,3)*ψ_d.diff(θ)-ψ_d.diff(η,2,θ,1)*ψ_d.diff(η)+ϵ*ψ_d.diff(η,2,θ,2) ));
trigsimp(diffeq.coeff(R^3)) |> string
```

    "-47*η^11*sin(2*θ)/30800 - 39*η^11*sin(4*θ)/123200 - 29*η^9*ϵ*sin(θ)/672 + 9*η^9*ϵ*sin(3*θ)/1120 + 61*η^9*sin(2*θ)/5376 - 27*η^9*sin(4*θ)/17920 - 27*η^7*ϵ^2*sin(2*θ)/560 + 577*η^7*ϵ*sin(θ)/11200 + 237*η^7*ϵ*sin(3*θ)/11200 - 603*η^7*sin(2*θ)/39200 + 3*η^7*sin(4*θ)/3136 + η^5*ϵ^3*sin(θ)/40 + 3*η^5*ϵ^2*sin(2*θ)/200 + 43*η^5*ϵ*sin(θ)/2240 - 3*η^5*ϵ*sin(3*θ)/64 + 123*η^5*sin(2*θ)/22400 + 69*η^5*sin(4*θ)/44800 - η^3*ϵ^3*sin(θ)/20 + 249*η^3*ϵ^2*sin(2*θ)/2800 - 321*η^3*ϵ*sin(θ)/11200 + 163*η^3*ϵ*sin(3*θ)/11200 + 29*η^3*sin(2*θ)/323400 - 13*η^3*sin(4*θ)/17600 + 27*η*ϵ^3*sin(θ)/1400 - 29*η*ϵ^2*sin(2*θ)/700 + 10673*η*ϵ*sin(θ)/2587200 + 15*η*ϵ*sin(3*θ)/34496 - 257*η*sin(2*θ)/3449600 + 257*η*sin(4*θ)/6899200 + Derivative(h4(η, θ), (η, 4))"

```julia
bcs= ((i4, -1, 0),(i4,1,0),(i4',-1,0),(i4',1,0))
h4= trigsimp(sympify(chop(split(dsolve(-47*η^11*sin(2*θ)/30800 - 39*η^11*sin(4*θ)/123200 - 29*η^9*ϵ*sin(θ)/672 + 9*η^9*ϵ*sin(3*θ)/1120 + 61*η^9*sin(2*θ)/5376 - 27*η^9*sin(4*θ)/17920 - 27*η^7*ϵ^2*sin(2*θ)/560 + 577*η^7*ϵ*sin(θ)/11200 + 237*η^7*ϵ*sin(3*θ)/11200 - 603*η^7*sin(2*θ)/39200 + 3*η^7*sin(4*θ)/3136 + η^5*ϵ^3*sin(θ)/40 + 3*η^5*ϵ^2*sin(2*θ)/200 + 43*η^5*ϵ*sin(θ)/2240 - 3*η^5*ϵ*sin(3*θ)/64 + 123*η^5*sin(2*θ)/22400 + 69*η^5*sin(4*θ)/44800 - η^3*ϵ^3*sin(θ)/20 + 249*η^3*ϵ^2*sin(2*θ)/2800 - 321*η^3*ϵ*sin(θ)/11200 + 163*η^3*ϵ*sin(3*θ)/11200 + 29*η^3*sin(2*θ)/323400 - 13*η^3*sin(4*θ)/17600 + 27*η*ϵ^3*sin(θ)/1400 - 29*η*ϵ^2*sin(2*θ)/700 + 10673*η*ϵ*sin(θ)/2587200 + 15*η*ϵ*sin(3*θ)/34496 - 257*η*sin(2*θ)/3449600 + 257*η*sin(4*θ)/6899200 + +  i4(η).diff(η, 4), i4(η), ics = bcs)|> string,", ")[2])))
```

$\begin{equation*}\frac{η \left(η - 1\right)^{2} \left(η + 1\right)^{2} \left(31584 η^{10} \sin{\left(2 θ \right)} + 6552 η^{10} \sin{\left(4 θ \right)} + 1705200 η^{8} ϵ \sin{\left(θ \right)} - 317520 η^{8} ϵ \sin{\left(3 θ \right)} - 385182 η^{8} \sin{\left(2 θ \right)} + 72639 η^{8} \sin{\left(4 θ \right)} + 4127760 η^{6} ϵ^{2} \sin{\left(2 θ \right)} - 1000188 η^{6} ϵ \sin{\left(θ \right)} - 2446668 η^{6} ϵ \sin{\left(3 θ \right)} + 515004 η^{6} \sin{\left(2 θ \right)} + 56826 η^{6} \sin{\left(4 θ \right)} - 5605600 η^{4} ϵ^{3} \sin{\left(θ \right)} + 4892160 η^{4} ϵ^{2} \sin{\left(2 θ \right)} - 8009876 η^{4} ϵ \sin{\left(θ \right)} + 5934684 η^{4} ϵ \sin{\left(3 θ \right)} + 183960 η^{4} \sin{\left(2 θ \right)} - 304332 η^{4} \sin{\left(4 θ \right)} + 29149120 η^{2} ϵ^{3} \sin{\left(θ \right)} - 66127152 η^{2} ϵ^{2} \sin{\left(2 θ \right)} + 8115548 η^{2} ϵ \sin{\left(θ \right)} + 2568300 η^{2} ϵ \sin{\left(3 θ \right)} - 219468 η^{2} \sin{\left(2 θ \right)} - 69258 η^{2} \sin{\left(4 θ \right)} - 45069024 ϵ^{3} \sin{\left(θ \right)} + 96943392 ϵ^{2} \sin{\left(2 θ \right)} + 931140 ϵ \sin{\left(θ \right)} - 3255084 ϵ \sin{\left(3 θ \right)} - 201930 \sin{\left(2 θ \right)} - 44667 \sin{\left(4 θ \right)}\right)}{678053376000}\end{equation*}$

## Fifth term

```julia
ψ_d = h1 + R*h2 + R^2*h3 + R^3*h4 + R^4*h5(η,θ)
diffeq = expand( ψ_d.diff(η,4) +  R*(ψ_d.diff(η,3)*ψ_d.diff(θ)-ψ_d.diff(η,2,θ,1)*ψ_d.diff(η)+ϵ*ψ_d.diff(η,2,θ,2) ));
trigsimp(diffeq.coeff(R^4)) |> string
```

    "3*η^15*sin(θ)^5/98000 + 71*η^15*sin(θ)^3/2002000 - 2819*η^15*sin(θ)/21021000 + 89*η^13*ϵ*sin(θ)^3*cos(θ)/123200 - η^13*ϵ*sin(θ)*cos(θ)^3/5600 - 2823*η^13*ϵ*sin(θ)*cos(θ)/1601600 - 27*η^13*ϵ*sin(θ)*cos(3*θ)/83200 + 27*η^13*ϵ*sin(3*θ)*cos(θ)/70400 + 183*η^13*sin(θ)^5/582400 - 103*η^13*sin(θ)^3/145600 + 29*η^13*sin(θ)/36400 - η^11*ϵ^2*sin(θ)^3/1100 - 1429*η^11*ϵ^2*sin(θ)/369600 + 81*η^11*ϵ^2*sin(3*θ)/123200 + 19*η^11*ϵ*sin(θ)^3*cos(θ)/7000 + η^11*ϵ*sin(θ)*cos(θ)^3/14000 + 6277*η^11*ϵ*sin(θ)*cos(θ)/1478400 - 837*η^11*ϵ*sin(θ)*cos(3*θ)/704000 + 373*η^11*ϵ*sin(3*θ)*cos(θ)/448000 + 29*η^11*sin(θ)^5/2464000 + 411*η^11*sin(θ)^3/308000 - 8*η^11*sin(θ)/4125 - η^9*ϵ^3*sin(θ)*cos(θ)/180 - 57*η^9*ϵ^2*sin(θ)^3/22400 + 7969*η^9*ϵ^2*sin(θ)/806400 + 237*η^9*ϵ^2*sin(3*θ)/89600 - 439*η^9*ϵ*sin(θ)^3*cos(θ)/94080 - 3*η^9*ϵ*sin(θ)*cos(θ)^3/19600 - η^9*ϵ*sin(θ)*cos(θ)/245 + 477*η^9*ϵ*sin(θ)*cos(3*θ)/89600 - 431*η^9*ϵ*sin(3*θ)*cos(θ)/89600 - 79*η^9*sin(θ)^5/78400 - 317*η^9*sin(θ)^3/235200 + η^9*sin(θ)/400 + η^7*ϵ^4*sin(θ)/1680 + 9*η^7*ϵ^3*sin(θ)*cos(θ)/2800 + 3113*η^7*ϵ^2*sin(θ)^3/196000 - 10901*η^7*ϵ^2*sin(θ)/2352000 - 9*η^7*ϵ^2*sin(3*θ)/896 - 831*η^7*ϵ*sin(θ)^3*cos(θ)/196000 + 11*η^7*ϵ*sin(θ)*cos(θ)^3/7000 + 2071*η^7*ϵ*sin(θ)*cos(θ)/784000 - 1503*η^7*ϵ*sin(θ)*cos(3*θ)/313600 + 1201*η^7*ϵ*sin(3*θ)*cos(θ)/224000 + 10357*η^7*sin(θ)^5/60368000 + 1791*η^7*sin(θ)^3/1078000 - 12893*η^7*sin(θ)/7546000 - η^5*ϵ^4*sin(θ)/400 + 507*η^5*ϵ^3*sin(θ)*cos(θ)/14000 - 33*η^5*ϵ^2*sin(θ)^3/1600 - 1137*η^5*ϵ^2*sin(θ)/224000 + 1467*η^5*ϵ^2*sin(3*θ)/224000 + 13127*η^5*ϵ*sin(θ)^3*cos(θ)/2156000 - 311*η^5*ϵ*sin(θ)*cos(θ)^3/196000 - 2531*η^5*ϵ*sin(θ)*cos(θ)/4312000 + 3441*η^5*ϵ*sin(θ)*cos(3*θ)/4312000 - 761*η^5*ϵ*sin(3*θ)*cos(θ)/431200 + 7947*η^5*sin(θ)^5/17248000 - 591*η^5*sin(θ)^3/616000 + 199*η^5*sin(θ)/404250 + 9*η^3*ϵ^4*sin(θ)/2800 - 7093*η^3*ϵ^3*sin(θ)*cos(θ)/126000 + 16767*η^3*ϵ^2*sin(θ)^3/2156000 + 362437*η^3*ϵ^2*sin(θ)/77616000 + 45*η^3*ϵ^2*sin(3*θ)/68992 - 6847*η^3*ϵ*sin(θ)^3*cos(θ)/6468000 + 27*η^3*ϵ*sin(θ)*cos(θ)^3/98000 - 128417*η^3*ϵ*sin(θ)*cos(θ)/672672000 + 14257*η^3*ϵ*sin(θ)*cos(3*θ)/40768000 - 38173*η^3*ϵ*sin(3*θ)*cos(θ)/1345344000 - 85517*η^3*sin(θ)^5/941740800 + 55859*η^3*sin(θ)^3/588588000 - 37*η^3*sin(θ)/1681680 - 19*η*ϵ^4*sin(θ)/18000 + 59527*η*ϵ^3*sin(θ)*cos(θ)/3234000 - 7559*η*ϵ^2*sin(θ)^3/5174400 - 223331*η*ϵ^2*sin(θ)/4036032000 - 324231*η*ϵ^2*sin(3*θ)/448448000 + 401*η*ϵ*sin(θ)^3*cos(θ)/30576000 - 115*η*ϵ*sin(θ)*cos(θ)/4708704 - 34663*η*ϵ*sin(θ)*cos(3*θ)/448448000 + 34663*η*ϵ*sin(3*θ)*cos(θ)/1345344000 + 67*η*sin(θ)^5/22422400 - 67*η*sin(θ)^3/47087040 + Derivative(h5(η, θ), (η, 4))"

```julia
bcs= ((i5, -1, 0),(i5,1,0),(i5',-1,0),(i5',1,0))
h5=  trigsimp(sympify(chop(split(dsolve( 3*η^15*sin(θ)^5/98000 + 71*η^15*sin(θ)^3/2002000 - 2819*η^15*sin(θ)/21021000 + 89*η^13*ϵ*sin(θ)^3*cos(θ)/123200 - η^13*ϵ*sin(θ)*cos(θ)^3/5600 - 2823*η^13*ϵ*sin(θ)*cos(θ)/1601600 - 27*η^13*ϵ*sin(θ)*cos(3*θ)/83200 + 27*η^13*ϵ*sin(3*θ)*cos(θ)/70400 + 183*η^13*sin(θ)^5/582400 - 103*η^13*sin(θ)^3/145600 + 29*η^13*sin(θ)/36400 - η^11*ϵ^2*sin(θ)^3/1100 - 1429*η^11*ϵ^2*sin(θ)/369600 + 81*η^11*ϵ^2*sin(3*θ)/123200 + 19*η^11*ϵ*sin(θ)^3*cos(θ)/7000 + η^11*ϵ*sin(θ)*cos(θ)^3/14000 + 6277*η^11*ϵ*sin(θ)*cos(θ)/1478400 - 837*η^11*ϵ*sin(θ)*cos(3*θ)/704000 + 373*η^11*ϵ*sin(3*θ)*cos(θ)/448000 + 29*η^11*sin(θ)^5/2464000 + 411*η^11*sin(θ)^3/308000 - 8*η^11*sin(θ)/4125 - η^9*ϵ^3*sin(θ)*cos(θ)/180 - 57*η^9*ϵ^2*sin(θ)^3/22400 + 7969*η^9*ϵ^2*sin(θ)/806400 + 237*η^9*ϵ^2*sin(3*θ)/89600 - 439*η^9*ϵ*sin(θ)^3*cos(θ)/94080 - 3*η^9*ϵ*sin(θ)*cos(θ)^3/19600 - η^9*ϵ*sin(θ)*cos(θ)/245 + 477*η^9*ϵ*sin(θ)*cos(3*θ)/89600 - 431*η^9*ϵ*sin(3*θ)*cos(θ)/89600 - 79*η^9*sin(θ)^5/78400 - 317*η^9*sin(θ)^3/235200 + η^9*sin(θ)/400 + η^7*ϵ^4*sin(θ)/1680 + 9*η^7*ϵ^3*sin(θ)*cos(θ)/2800 + 3113*η^7*ϵ^2*sin(θ)^3/196000 - 10901*η^7*ϵ^2*sin(θ)/2352000 - 9*η^7*ϵ^2*sin(3*θ)/896 - 831*η^7*ϵ*sin(θ)^3*cos(θ)/196000 + 11*η^7*ϵ*sin(θ)*cos(θ)^3/7000 + 2071*η^7*ϵ*sin(θ)*cos(θ)/784000 - 1503*η^7*ϵ*sin(θ)*cos(3*θ)/313600 + 1201*η^7*ϵ*sin(3*θ)*cos(θ)/224000 + 10357*η^7*sin(θ)^5/60368000 + 1791*η^7*sin(θ)^3/1078000 - 12893*η^7*sin(θ)/7546000 - η^5*ϵ^4*sin(θ)/400 + 507*η^5*ϵ^3*sin(θ)*cos(θ)/14000 - 33*η^5*ϵ^2*sin(θ)^3/1600 - 1137*η^5*ϵ^2*sin(θ)/224000 + 1467*η^5*ϵ^2*sin(3*θ)/224000 + 13127*η^5*ϵ*sin(θ)^3*cos(θ)/2156000 - 311*η^5*ϵ*sin(θ)*cos(θ)^3/196000 - 2531*η^5*ϵ*sin(θ)*cos(θ)/4312000 + 3441*η^5*ϵ*sin(θ)*cos(3*θ)/4312000 - 761*η^5*ϵ*sin(3*θ)*cos(θ)/431200 + 7947*η^5*sin(θ)^5/17248000 - 591*η^5*sin(θ)^3/616000 + 199*η^5*sin(θ)/404250 + 9*η^3*ϵ^4*sin(θ)/2800 - 7093*η^3*ϵ^3*sin(θ)*cos(θ)/126000 + 16767*η^3*ϵ^2*sin(θ)^3/2156000 + 362437*η^3*ϵ^2*sin(θ)/77616000 + 45*η^3*ϵ^2*sin(3*θ)/68992 - 6847*η^3*ϵ*sin(θ)^3*cos(θ)/6468000 + 27*η^3*ϵ*sin(θ)*cos(θ)^3/98000 - 128417*η^3*ϵ*sin(θ)*cos(θ)/672672000 + 14257*η^3*ϵ*sin(θ)*cos(3*θ)/40768000 - 38173*η^3*ϵ*sin(3*θ)*cos(θ)/1345344000 - 85517*η^3*sin(θ)^5/941740800 + 55859*η^3*sin(θ)^3/588588000 - 37*η^3*sin(θ)/1681680 - 19*η*ϵ^4*sin(θ)/18000 + 59527*η*ϵ^3*sin(θ)*cos(θ)/3234000 - 7559*η*ϵ^2*sin(θ)^3/5174400 - 223331*η*ϵ^2*sin(θ)/4036032000 - 324231*η*ϵ^2*sin(3*θ)/448448000 + 401*η*ϵ*sin(θ)^3*cos(θ)/30576000 - 115*η*ϵ*sin(θ)*cos(θ)/4708704 - 34663*η*ϵ*sin(θ)*cos(3*θ)/448448000 + 34663*η*ϵ*sin(3*θ)*cos(θ)/1345344000 + 67*η*sin(θ)^5/22422400 - 67*η*sin(θ)^3/47087040 + i5(η).diff(η, 4),i5(η), ics = bcs)|> string,", ")[2])))
```

$\begin{equation*}\frac{η \left(η - 1\right)^{2} \left(η + 1\right)^{2} \left(- 166486320 η^{14} \sin^{5}{\left(θ \right)} - 192875760 η^{14} \sin^{3}{\left(θ \right)} + 729331680 η^{14} \sin{\left(θ \right)} - 6398371980 η^{12} ϵ \sin^{3}{\left(θ \right)} \cos{\left(θ \right)} + 1581620040 η^{12} ϵ \sin{\left(θ \right)} \cos^{3}{\left(θ \right)} + 15611585220 η^{12} ϵ \sin{\left(θ \right)} \cos{\left(θ \right)} + 2874290265 η^{12} ϵ \sin{\left(θ \right)} \cos{\left(3 θ \right)} - 3396888495 η^{12} ϵ \sin{\left(3 θ \right)} \cos{\left(θ \right)} - 3116015595 η^{12} \sin^{5}{\left(θ \right)} + 5879897100 η^{12} \sin^{3}{\left(θ \right)} - 5597795280 η^{12} \sin{\left(θ \right)} + 14039182080 η^{10} ϵ^{2} \sin^{3}{\left(θ \right)} + 59708307120 η^{10} ϵ^{2} \sin{\left(θ \right)} - 10153337040 η^{10} ϵ^{2} \sin{\left(3 θ \right)} - 54713730456 η^{10} ϵ \sin^{3}{\left(θ \right)} \cos{\left(θ \right)} + 2060161488 η^{10} ϵ \sin{\left(θ \right)} \cos^{3}{\left(θ \right)} - 34345241700 η^{10} ϵ \sin{\left(θ \right)} \cos{\left(θ \right)} + 24109198344 η^{10} ϵ \sin{\left(θ \right)} \cos{\left(3 θ \right)} - 19651536828 η^{10} ϵ \sin{\left(3 θ \right)} \cos{\left(θ \right)} - 6247302138 η^{10} \sin^{5}{\left(θ \right)} - 8654843736 η^{10} \sin^{3}{\left(θ \right)} + 18025332864 η^{10} \sin{\left(θ \right)} + 163790457600 η^{8} ϵ^{3} \sin{\left(θ \right)} \cos{\left(θ \right)} + 103100243400 η^{8} ϵ^{2} \sin^{3}{\left(θ \right)} - 171932974290 η^{8} ϵ^{2} \sin{\left(θ \right)} - 98289943290 η^{8} ϵ^{2} \sin{\left(3 θ \right)} + 34542360468 η^{8} ϵ \sin^{3}{\left(θ \right)} \cos{\left(θ \right)} + 7051297176 η^{8} ϵ \sin{\left(θ \right)} \cos^{3}{\left(θ \right)} + 36033777780 η^{8} ϵ \sin{\left(θ \right)} \cos{\left(θ \right)} - 111609561987 η^{8} ϵ \sin{\left(θ \right)} \cos{\left(3 θ \right)} + 105911490069 η^{8} ϵ \sin{\left(3 θ \right)} \cos{\left(θ \right)} + 20329323399 η^{8} \sin^{5}{\left(θ \right)} + 16546314708 η^{8} \sin^{3}{\left(θ \right)} - 32057244912 η^{8} \sin{\left(θ \right)} - 38022784800 η^{6} ϵ^{4} \sin{\left(θ \right)} + 122257877280 η^{6} ϵ^{3} \sin{\left(θ \right)} \cos{\left(θ \right)} - 822395230272 η^{6} ϵ^{2} \sin^{3}{\left(θ \right)} - 107512557768 η^{6} ϵ^{2} \sin{\left(θ \right)} + 455207943960 η^{6} ϵ^{2} \sin{\left(3 θ \right)} + 394629315696 η^{6} ϵ \sin^{3}{\left(θ \right)} \cos{\left(θ \right)} - 88337719008 η^{6} ϵ \sin{\left(θ \right)} \cos^{3}{\left(θ \right)} - 62326889856 η^{6} ϵ \sin{\left(θ \right)} \cos{\left(θ \right)} + 58822993152 η^{6} ϵ \sin{\left(θ \right)} \cos{\left(3 θ \right)} - 111015717120 η^{6} ϵ \sin{\left(3 θ \right)} \cos{\left(θ \right)} + 35946710100 η^{6} \sin^{5}{\left(θ \right)} - 64380538656 η^{6} \sin^{3}{\left(θ \right)} + 27001794624 η^{6} \sin{\left(θ \right)} + 342205063200 η^{4} ϵ^{4} \sin{\left(θ \right)} - 5977933869600 η^{4} ϵ^{3} \sin{\left(θ \right)} \cos{\left(θ \right)} + 1702677016656 η^{4} ϵ^{2} \sin^{3}{\left(θ \right)} + 806106018564 η^{4} ϵ^{2} \sin{\left(θ \right)} - 86961451500 η^{4} ϵ^{2} \sin{\left(3 θ \right)} - 263906374116 η^{4} ϵ \sin^{3}{\left(θ \right)} \cos{\left(θ \right)} + 81734380728 η^{4} ϵ \sin{\left(θ \right)} \cos^{3}{\left(θ \right)} - 62487895932 η^{4} ϵ \sin{\left(θ \right)} \cos{\left(θ \right)} + 95749015131 η^{4} ϵ \sin{\left(θ \right)} \cos{\left(3 θ \right)} - 32684360709 η^{4} ϵ \sin{\left(3 θ \right)} \cos{\left(θ \right)} - 25519339629 η^{4} \sin^{5}{\left(θ \right)} + 15203078100 η^{4} \sin^{3}{\left(θ \right)} + 3703999600 η^{4} \sin{\left(θ \right)} - 1213470017760 η^{2} ϵ^{4} \sin{\left(θ \right)} + 21826465680096 η^{2} ϵ^{3} \sin{\left(θ \right)} \cos{\left(θ \right)} - 456130160640 η^{2} ϵ^{2} \sin^{3}{\left(θ \right)} - 1092696640728 η^{2} ϵ^{2} \sin{\left(θ \right)} - 1021968291960 η^{2} ϵ^{2} \sin{\left(3 θ \right)} - 284869800600 η^{2} ϵ \sin^{3}{\left(θ \right)} \cos{\left(θ \right)} + 85871943696 η^{2} ϵ \sin{\left(θ \right)} \cos^{3}{\left(θ \right)} + 52330029444 η^{2} ϵ \sin{\left(θ \right)} \cos{\left(θ \right)} - 77948956008 η^{2} ϵ \sin{\left(θ \right)} \cos{\left(3 θ \right)} + 62736207996 η^{2} ϵ \sin{\left(3 θ \right)} \cos{\left(θ \right)} - 32293847178 η^{2} \sin^{5}{\left(θ \right)} + 37628191080 η^{2} \sin^{3}{\left(θ \right)} - 6342526624 η^{2} \sin{\left(θ \right)} + 1681041634272 ϵ^{4} \sin{\left(θ \right)} - 27970813997280 ϵ^{3} \sin{\left(θ \right)} \cos{\left(θ \right)} + 3543939025704 ϵ^{2} \sin^{3}{\left(θ \right)} - 2758211757378 ϵ^{2} \sin{\left(θ \right)} + 1091197665558 ϵ^{2} \sin{\left(3 θ \right)} - 361125041508 ϵ \sin^{3}{\left(θ \right)} \cos{\left(θ \right)} + 90009506664 ϵ \sin{\left(θ \right)} \cos^{3}{\left(θ \right)} + 270113894820 ϵ \sin{\left(θ \right)} \cos{\left(θ \right)} + 74228185647 ϵ \sin{\left(θ \right)} \cos{\left(3 θ \right)} + 49531739103 ϵ \sin{\left(3 θ \right)} \cos{\left(θ \right)} - 51666013647 \sin^{5}{\left(θ \right)} + 66052189260 \sin^{3}{\left(θ \right)} - 16389052848 \sin{\left(θ \right)}\right)}{505915965434880000}\end{equation*}$

```julia
ψ2_d = h1 + R*h2;
ψ3_d=  h1 + R*h2 + R^2*h3;
ψ4_d = h1 + R*h2 + R^2*h3 + R^3*h4;
ψ5_d = h1 + R*h2 + R^2*h3 + R^3*h4 + R^4*h5 ;
```

```julia
Reynolds= 60.0
η_value = 0.9
ϵ_value = 0.1

plot(x->ψ2_d.subs([(θ, x), (R, Reynolds), (η, η_value), (ϵ, ϵ_value)]),0,pi, linecolor=:red, linestyle=:dash, linewidth=2, label="2 terms in series")
plot!(x->ψ3_d.subs([(θ, x), (R, Reynolds), (η, η_value), (ϵ, ϵ_value)]),0,pi, linestyle=:dashdot,linewidth=3, label="3 terms in series")
plot!(x->ψ4_d.subs([(θ, x), (R, Reynolds), (η, η_value), (ϵ, ϵ_value)]),0,pi, linestyle=:dot,linewidth=3, label="4 terms in series")
plot!(x->ψ5_d.subs([(θ, x), (R, Reynolds), (η, η_value), (ϵ, ϵ_value)]),0,pi, linestyle=:dot,linewidth=2, label="5 terms in series")
xticks!(([0:π/6:π;], ["0", "π", "π/3", "π/2", "2π/3", "5π/6","π"]))
plot!(title= "Asymptotic series at "*L"\eta=%$η_value, \quad R_s= %$Reynolds,\quad ϵ = %$ϵ_value ",size=(1100,500), legend=:outertopright, xlabel =L"η", ylabel=L"Ψ", yguidefontrotation=-90)
```

```julia
h1|>string
```

    "η*(1 - η^2)*sin(θ)/2"

```julia
SymPy.simplify(h5) |> string
```

    "η*(η - 1)^2*(η + 1)^2*(-166486320*η^14*sin(θ)^5 - 192875760*η^14*sin(θ)^3 + 729331680*η^14*sin(θ) - 6398371980*η^12*ϵ*sin(θ)^3*cos(θ) + 1581620040*η^12*ϵ*sin(θ)*cos(θ)^3 + 2874290265*η^12*ϵ*sin(θ)*cos(3*θ) + 7805792610*η^12*ϵ*sin(2*θ) - 3396888495*η^12*ϵ*sin(3*θ)*cos(θ) - 3116015595*η^12*sin(θ)^5 + 5879897100*η^12*sin(θ)^3 - 5597795280*η^12*sin(θ) + 14039182080*η^10*ϵ^2*sin(θ)^3 + 59708307120*η^10*ϵ^2*sin(θ) - 10153337040*η^10*ϵ^2*sin(3*θ) - 54713730456*η^10*ϵ*sin(θ)^3*cos(θ) + 2060161488*η^10*ϵ*sin(θ)*cos(θ)^3 + 24109198344*η^10*ϵ*sin(θ)*cos(3*θ) - 17172620850*η^10*ϵ*sin(2*θ) - 19651536828*η^10*ϵ*sin(3*θ)*cos(θ) - 6247302138*η^10*sin(θ)^5 - 8654843736*η^10*sin(θ)^3 + 18025332864*η^10*sin(θ) + 81895228800*η^8*ϵ^3*sin(2*θ) + 103100243400*η^8*ϵ^2*sin(θ)^3 - 171932974290*η^8*ϵ^2*sin(θ) - 98289943290*η^8*ϵ^2*sin(3*θ) + 34542360468*η^8*ϵ*sin(θ)^3*cos(θ) + 7051297176*η^8*ϵ*sin(θ)*cos(θ)^3 - 111609561987*η^8*ϵ*sin(θ)*cos(3*θ) + 18016888890*η^8*ϵ*sin(2*θ) + 105911490069*η^8*ϵ*sin(3*θ)*cos(θ) + 20329323399*η^8*sin(θ)^5 + 16546314708*η^8*sin(θ)^3 - 32057244912*η^8*sin(θ) - 38022784800*η^6*ϵ^4*sin(θ) + 61128938640*η^6*ϵ^3*sin(2*θ) - 822395230272*η^6*ϵ^2*sin(θ)^3 - 107512557768*η^6*ϵ^2*sin(θ) + 455207943960*η^6*ϵ^2*sin(3*θ) + 394629315696*η^6*ϵ*sin(θ)^3*cos(θ) - 88337719008*η^6*ϵ*sin(θ)*cos(θ)^3 + 58822993152*η^6*ϵ*sin(θ)*cos(3*θ) - 31163444928*η^6*ϵ*sin(2*θ) - 111015717120*η^6*ϵ*sin(3*θ)*cos(θ) + 35946710100*η^6*sin(θ)^5 - 64380538656*η^6*sin(θ)^3 + 27001794624*η^6*sin(θ) + 342205063200*η^4*ϵ^4*sin(θ) - 2988966934800*η^4*ϵ^3*sin(2*θ) + 1702677016656*η^4*ϵ^2*sin(θ)^3 + 806106018564*η^4*ϵ^2*sin(θ) - 86961451500*η^4*ϵ^2*sin(3*θ) - 263906374116*η^4*ϵ*sin(θ)^3*cos(θ) + 81734380728*η^4*ϵ*sin(θ)*cos(θ)^3 + 95749015131*η^4*ϵ*sin(θ)*cos(3*θ) - 31243947966*η^4*ϵ*sin(2*θ) - 32684360709*η^4*ϵ*sin(3*θ)*cos(θ) - 25519339629*η^4*sin(θ)^5 + 15203078100*η^4*sin(θ)^3 + 3703999600*η^4*sin(θ) - 1213470017760*η^2*ϵ^4*sin(θ) + 10913232840048*η^2*ϵ^3*sin(2*θ) - 456130160640*η^2*ϵ^2*sin(θ)^3 - 1092696640728*η^2*ϵ^2*sin(θ) - 1021968291960*η^2*ϵ^2*sin(3*θ) - 284869800600*η^2*ϵ*sin(θ)^3*cos(θ) + 85871943696*η^2*ϵ*sin(θ)*cos(θ)^3 - 77948956008*η^2*ϵ*sin(θ)*cos(3*θ) + 26165014722*η^2*ϵ*sin(2*θ) + 62736207996*η^2*ϵ*sin(3*θ)*cos(θ) - 32293847178*η^2*sin(θ)^5 + 37628191080*η^2*sin(θ)^3 - 6342526624*η^2*sin(θ) + 1681041634272*ϵ^4*sin(θ) - 13985406998640*ϵ^3*sin(2*θ) + 3543939025704*ϵ^2*sin(θ)^3 - 2758211757378*ϵ^2*sin(θ) + 1091197665558*ϵ^2*sin(3*θ) - 361125041508*ϵ*sin(θ)^3*cos(θ) + 90009506664*ϵ*sin(θ)*cos(θ)^3 + 74228185647*ϵ*sin(θ)*cos(3*θ) + 135056947410*ϵ*sin(2*θ) + 49531739103*ϵ*sin(3*θ)*cos(θ) - 51666013647*sin(θ)^5 + 66052189260*sin(θ)^3 - 16389052848*sin(θ))/505915965434880000"

# The full Navier Stokes equation for $\Psi$

```julia
j1, j2, j3, j4, j5, j6 = symbols("j1 j2 j3 j4 j5 j6", cls=sympy.Function)
@symfuns k1 k2 k3 k4 k5 k6
α, ρ, R, θ, r, ϕ = symbols("α ρ R θ r ϕ")
ϵ = symbols("ϵ");
```

```julia
equation1 =(k1''(ρ)+1/ρ*k1'(ρ)-4/ρ^2*k1(ρ)).diff(ρ,2)+(k1''(ρ)+1/ρ*k1'(ρ)-4/ρ^2*k1(ρ)).diff(ρ,1)*1/ρ+-4*(k1''(ρ)+1/ρ*k1'(ρ)-4/ρ^2*k1(ρ))/ρ^2
```

$\frac{d^{4}}{d ρ^{4}} \operatorname{k_{1}}{\left(ρ \right)} + \frac{\frac{d^{3}}{d ρ^{3}} \operatorname{k_{1}}{\left(ρ \right)} + \frac{\frac{d^{2}}{d ρ^{2}} \operatorname{k_{1}}{\left(ρ \right)}}{ρ} - \frac{5 \frac{d}{d ρ} \operatorname{k_{1}}{\left(ρ \right)}}{ρ^{2}} + \frac{8 \operatorname{k_{1}}{\left(ρ \right)}}{ρ^{3}}}{ρ} + \frac{\frac{d^{3}}{d ρ^{3}} \operatorname{k_{1}}{\left(ρ \right)}}{ρ} + \frac{- 4 \frac{d^{2}}{d ρ^{2}} \operatorname{k_{1}}{\left(ρ \right)} - \frac{4 \frac{d}{d ρ} \operatorname{k_{1}}{\left(ρ \right)}}{ρ} + \frac{16 \operatorname{k_{1}}{\left(ρ \right)}}{ρ^{2}}}{ρ^{2}} - \frac{6 \frac{d^{2}}{d ρ^{2}} \operatorname{k_{1}}{\left(ρ \right)}}{ρ^{2}} + \frac{18 \frac{d}{d ρ} \operatorname{k_{1}}{\left(ρ \right)}}{ρ^{3}} - \frac{24 \operatorname{k_{1}}{\left(ρ \right)}}{ρ^{4}}$

```julia
bcs= ((k1, 1, 0),(k1,α,0),(k1',1, 3*α^4/(2*(α^2-1)^2)),(k1',α,3/(2*α*(α^2-1)^2)))
solution1 = chop(split(dsolve(equation1, k1(ρ),ics = bcs)|> string,", ")[2])
```

    ┌ Warning: `vendor()` is deprecated, use `BLAS.get_config()` and inspect the output instead
    │   caller = npyinitialize() at numpy.jl:67
    └ @ PyCall /home/comet/.julia/packages/PyCall/L0fLP/src/numpy.jl:67

    "ρ^4*(3*α^4 + 3)/(4*α^8 - 16*α^6 + 24*α^4 - 16*α^2 + 4) + ρ^2*(-6*α^6 - 3*α^4 - 3*α^2 - 6)/(4*α^8 - 16*α^6 + 24*α^4 - 16*α^2 + 4) + (3*α^8 + 6*α^6 + 6*α^2 + 3)/(4*α^8 - 16*α^6 + 24*α^4 - 16*α^2 + 4) + (-3*α^8 - 3*α^2)/(ρ^2*(4*α^8 - 16*α^6 + 24*α^4 - 16*α^2 + 4))"

```julia
gsolution =sin(2*θ)*sympify(solution1)
factor(gsolution)|>string
```

    "3*(α - ρ)*(α + ρ)*(ρ - 1)*(ρ + 1)*(α^6 - α^4*ρ^2 - ρ^2 + 1)*sin(2*θ)/(4*ρ^2*(α - 1)^4*(α + 1)^4)"

```julia
factor(gsolution.diff(ρ,1).subs([(ρ, 1)]))
```

$\frac{3 α^{4} \sin{\left(2 θ \right)}}{2 \left(α - 1\right)^{2} \left(α + 1\right)^{2}}$

```julia
factor(gsolution.diff(ρ,1).subs([(ρ, α)]))
```

$\frac{3 \sin{\left(2 θ \right)}}{2 α \left(α - 1\right)^{2} \left(α + 1\right)^{2}}$

```julia
RileySolution = 3*sin(2*θ)/(4*(α^2-1)^4)*((2α^6+α^4+α^2+2)*r^2 -(α^4+1)*r^4 +α^2*(α^6+1)*r^-2 - (α^8+2α^6+2α^2+1))
```

$\frac{3 \left(- r^{4} \left(α^{4} + 1\right) + r^{2} \left(2 α^{6} + α^{4} + α^{2} + 2\right) - α^{8} - 2 α^{6} - 2 α^{2} - 1 + \frac{α^{2} \left(α^{6} + 1\right)}{r^{2}}\right) \sin{\left(2 θ \right)}}{4 \left(α^{2} - 1\right)^{4}}$

```julia
SymPy.factor(RileySolution.diff(r,1).subs([(r, 1)]))
```

$- \frac{3 α^{4} \sin{\left(2 θ \right)}}{2 \left(α - 1\right)^{2} \left(α + 1\right)^{2}}$

```julia
SymPy.factor(RileySolution.diff(r,1).subs([(r, α)]))
```

$- \frac{3 \sin{\left(2 θ \right)}}{2 α \left(α - 1\right)^{2} \left(α + 1\right)^{2}}$

```julia
α_v = 20.0
xs = range(1, stop=α_v, length=100)
ys = range(0, stop=pi/2, length=100)

my_f(ρ,θ) = 3*(α_v - ρ)*(α_v + ρ)*(ρ - 1)*(ρ + 1)*(α_v^6 - α_v^4*ρ^2 - ρ^2 + 1)*sin(2*θ)/(4*ρ^2*(α_v - 1)^4*(α_v + 1)^4)
contour(xs, ys, my_f, xlabel="ρ", ylabel="ϕ",xlims=(0,α_v))
yticks!(([0:π/12:π/2;], ["0", "π/12", "π/6", "π/4", "π/3", "5π/12","π/2"]))

```

```julia
contour(xs, ys, my_f, xlabel="ρ", ylabel="ϕ", yguidefontrotation=-90)
yticks!(([0:π/12:π/2;], ["0", "π/12", "π/6", "π/4", "π/3", "5π/12","π/2"]))
```

```julia
streamfunction = (ρ-1)*(ρ-α)*sin(2*ϕ)*cos(5*ϕ)
```

$\left(- α + ρ\right) \left(ρ - 1\right) \sin{\left(2 ϕ \right)} \cos{\left(5 ϕ \right)}$

```julia
ω =-SymPy.trigsimp(streamfunction.diff(ρ,2)+streamfunction.diff(ρ,1)*1/ρ +streamfunction.diff(ϕ,2)*1/ρ^2)|>string
```

    "-2*sin(2*ϕ)*cos(5*ϕ) - (-sin(3*ϕ) + sin(7*ϕ))*(-α + 2*ρ - 1)/(2*ρ) - (α - ρ)*(ρ - 1)*(-9*sin(3*ϕ) + 49*sin(7*ϕ))/(2*ρ^2)"

```julia
ω.subs(ρ,α).subs(α,4)
```

```julia
ω
```

    "-2*sin(2*ϕ)*cos(5*ϕ) - (-sin(3*ϕ) + sin(7*ϕ))*(-α + 2*ρ - 1)/(2*ρ) - (α - ρ)*(ρ - 1)*(-9*sin(3*ϕ) + 49*sin(7*ϕ))/(2*ρ^2)"

```julia
myfunct1(ρ,ϕ)=(ρ-1)*(ρ-α_v)*sin(2*ϕ)*cos(5*ϕ)
```

    myfunct1 (generic function with 1 method)

```julia
α_v = 20.0
xs = range(1, stop=α_v, length=100)
ys = range(0, stop=pi/2, length=100)
surface(xs, ys, myfunct1, xlabel="ρ", ylabel="ϕ")
yticks!(([0:π/12:π/2;], ["0", "π/12", "π/6", "π/4", "π/3", "5π/12","π/2"]))

```

```julia
plot([1,1.5,1.7],[2,2.5,2],[3,3.5,3.5], proj=:polar)
```

```julia
pyplot()
α_v = 20.8
xs = range(1, stop=α_v, length=100)
ys = range(0, stop=pi/2, length=100)
my_f2(θ,ρ) = 3*(α_v - ρ)*(α_v + ρ)*(ρ - 1)*(ρ + 1)*(α_v^6 - α_v^4*ρ^2 - ρ^2 + 1)*sin(2*θ)/(4*ρ^2*(α_v - 1)^4*(α_v + 1)^4)
contour( ys, xs, my_f2, ylabel="ρ", xlabel="ϕ",xlims=(0,pi/2), proj=:polar)
xticks!(([0:π/12:π/2;], ["0", "π/12", "π/6", "π/4", "π/3", "5π/12","π/2"]))
```

```julia

```


Sympy to calculate partial derivatives
======================================

```
from sympy import Symbol, symbols, Matrix, diff, expand
```

```
x, y = symbols('x,y')
```

```
p0,p1,p2,p3,p4,p5,p6,p7 = symbols('p0,p1,p2,p3,p4,p5,p6,p7')
```

```
H = Matrix([(p0+1,p3,p6), (p1,p4+1,p7), (p2,p5,1.0)])
P = Matrix([(x),(y),(1.0)])
H
```

    [p0 + 1,     p3,  p6]
    [    p1, p4 + 1,  p7]
    [    p2,     p5, 1.0]

```
equations = H*P
```

```
equations
```

    [p3*y + 1.0*p6 + x*(p0 + 1)]
    [p1*x + 1.0*p7 + y*(p4 + 1)]
    [         p2*x + p5*y + 1.0]

```
xequation = equations[0] / equations[2]
```

```
yequation = equations[1] / equations[2]
```

Formulate equations for partial derivatives:

```
for var in (p0,p1,p2,p3,p4,p5,p6,p7):
    eq = diff(xequation, var)
    print '{}: {}'.format(var, eq)
```

    p0: x/(p2*x + p5*y + 1.0)
    p1: 0
    p2: -x*(p3*y + 1.0*p6 + x*(p0 + 1))/(p2*x + p5*y + 1.0)**2
    p3: y/(p2*x + p5*y + 1.0)
    p4: 0
    p5: -y*(p3*y + 1.0*p6 + x*(p0 + 1))/(p2*x + p5*y + 1.0)**2
    p6: 1.0/(p2*x + p5*y + 1.0)
    p7: 0

```
for var in (p0,p1,p2,p3,p4,p5,p6,p7):
    eq = diff(yequation, var)
    print '{}: {}'.format(var, eq)
```

    p0: 0
    p1: x/(p2*x + p5*y + 1.0)
    p2: -x*(p1*x + 1.0*p7 + y*(p4 + 1))/(p2*x + p5*y + 1.0)**2
    p3: 0
    p4: y/(p2*x + p5*y + 1.0)
    p5: -y*(p1*x + 1.0*p7 + y*(p4 + 1))/(p2*x + p5*y + 1.0)**2
    p6: 0
    p7: 1.0/(p2*x + p5*y + 1.0)

```

```