# Fun with Hidden Markov Models
*by Loren Lugosch*

This notebook introduces the Hidden Markov Model (HMM), a simple model for sequential data.

We will see:
- what an HMM is and when you might want to use it;
- the so-called "three problems" of an HMM; and
- how to implement an HMM in PyTorch.

(The code in this notebook can also be found at https://github.com/lorenlugosch/pytorch_HMM.)

A hypothetical scenario
------

To motivate the use of HMMs, imagine that you have a friend who gets to do a lot of travelling. Every day, this jet-setting friend sends you a selfie from the city they’re in, to make you envious.

How would you go about guessing which city the friend is in each day, just by looking at the selfies?

If the selfie contains a really obvious landmark, like the Eiffel Tower, it will be easy to figure out where the photo was taken. If not, it will be a lot harder to infer the city.

But we have a clue to help us: the city the friend is in each day is not totally random. For example, the friend will probably remain in the same city for a few days to sightsee before flying to a new city.

## The HMM setup

The hypothetical scenario of the friend travelling between cities and sending you selfies can be modeled using an HMM.

An HMM models a system that is in a particular state at any given time and produces an output that depends on that state.

At each timestep or clock tick, the system randomly decides on a new state and jumps into that state. The system then randomly generates an observation. The states are "hidden": we can't observe them. (In the cities/selfies analogy, the unknown cities would be the hidden states, and the selfies would be the observations.)

Let's denote the sequence of states as $\mathbf{z} = \{z_1, z_2, \dots, z_T \}$, where each state is one of a finite set of $N$ states, and the sequence of observations as $\mathbf{x} = \{x_1, x_2, \dots, x_T\}$. The observations could be discrete, like letters, or real-valued, like audio frames.

An HMM makes two key assumptions:
- **Assumption 1:** The state at time $t$ depends *only* on the state at the previous time $t-1$.
- **Assumption 2:** The output at time $t$ depends *only* on the state at time $t$.

These two assumptions make it possible to efficiently compute certain quantities that we may be interested in.

## Components of an HMM
An HMM has three sets of trainable parameters.

- The **transition model** is a square matrix $A$, where $A_{s, s'}$ represents $p(z_t = s|z_{t-1} = s')$, the probability of jumping from state $s'$ to state $s$.

- The **emission model** $b_s(x_t)$ tells us $p(x_t|z_t = s)$, the probability of generating $x_t$ when the system is in state $s$. For discrete observations, which we will use in this notebook, the emission model is just a lookup table, with one row for each state, and one column for each observation. For real-valued observations, it is common to use a Gaussian mixture model or neural network to implement the emission model.

- The **state priors** tell us $p(z_1 = s)$, the probability of starting in state $s$. We use $\pi$ to denote the vector of state priors, so $\pi_s$ is the state prior for state $s$.

Let's program an HMM class in PyTorch.

```
import torch
import numpy as np

class HMM(torch.nn.Module):
  """
  Hidden Markov Model with discrete observations.
  """
  def __init__(self, M, N):
    super(HMM, self).__init__()
    self.M = M # number of possible observations
    self.N = N # number of states

    # A
    self.transition_model = TransitionModel(self.N)

    # b(x_t)
    self.emission_model = EmissionModel(self.N,self.M)

    # pi
    self.unnormalized_state_priors = torch.nn.Parameter(torch.randn(self.N))

    # use the GPU
    self.is_cuda = torch.cuda.is_available()
    if self.is_cuda: self.cuda()

class TransitionModel(torch.nn.Module):
  def __init__(self, N):
    super(TransitionModel, self).__init__()
    self.N = N
    self.unnormalized_transition_matrix = torch.nn.Parameter(torch.randn(N,N))

class EmissionModel(torch.nn.Module):
  def __init__(self, N, M):
    super(EmissionModel, self).__init__()
    self.N = N
    self.M = M
    self.unnormalized_emission_matrix = torch.nn.Parameter(torch.randn(N,M))
```

To sample from the HMM, we start by picking a random initial state from the state prior distribution.

Then, we sample an output from the emission distribution, sample a transition from the transition distribution, and repeat.

(Notice that we pass the unnormalized model parameters through a softmax function to make them into probabilities.)

```
def sample(self, T=10):
  state_priors = torch.nn.functional.softmax(self.unnormalized_state_priors, dim=0)
  transition_matrix = torch.nn.functional.softmax(self.transition_model.unnormalized_transition_matrix, dim=0)
  emission_matrix = torch.nn.functional.softmax(self.emission_model.unnormalized_emission_matrix, dim=1)

  # sample initial state
  z_t = torch.distributions.categorical.Categorical(state_priors).sample().item()
  z = []; x = []
  z.append(z_t)
  for t in range(0,T):
    # sample emission
    x_t = torch.distributions.categorical.Categorical(emission_matrix[z_t]).sample().item()
    x.append(x_t)

    # sample transition
    z_t = torch.distributions.categorical.Categorical(transition_matrix[:,z_t]).sample().item()
    if t < T-1: z.append(z_t)

  return x, z

# Add the sampling method to our HMM class
HMM.sample = sample
```

Let's try hard-coding an HMM for generating fake words. (We'll also add some helper functions for encoding and decoding strings.)

We will assume that the system has one state for generating vowels and one state for generating consonants, and the transition matrix has 0s on the diagonal---in other words, the system cannot stay in the vowel state or the consonant state for one than one timestep; it has to switch.

Since we pass the transition matrix through a softmax, to get 0s we set the unnormalized parameter values to $-\infty$.

```
import string
alphabet = string.ascii_lowercase

def encode(s):
  """
  Convert a string into a list of integers
  """
  x = [alphabet.index(ss) for ss in s]
  return x

def decode(x):
  """
  Convert list of ints to string
  """
  s = "".join([alphabet[xx] for xx in x])
  return s

# Initialize the model
model = HMM(M=len(alphabet), N=2)

# Hard-wiring the parameters!
# Let state 0 = consonant, state 1 = vowel
for p in model.parameters():
    p.requires_grad = False # needed to do lines below
model.unnormalized_state_priors[0] = 0.    # Let's start with a consonant more frequently
model.unnormalized_state_priors[1] = -0.5
print("State priors:", torch.nn.functional.softmax(model.unnormalized_state_priors, dim=0))

# In state 0, only allow consonants; in state 1, only allow vowels
vowel_indices = torch.tensor([alphabet.index(letter) for letter in "aeiou"])
consonant_indices = torch.tensor([alphabet.index(letter) for letter in "bcdfghjklmnpqrstvwxyz"])
model.emission_model.unnormalized_emission_matrix[0, vowel_indices] = -np.inf
model.emission_model.unnormalized_emission_matrix[1, consonant_indices] = -np.inf
print("Emission matrix:", torch.nn.functional.softmax(model.emission_model.unnormalized_emission_matrix, dim=1))

# Only allow vowel -> consonant and consonant -> vowel
model.transition_model.unnormalized_transition_matrix[0,0] = -np.inf  # consonant -> consonant
model.transition_model.unnormalized_transition_matrix[0,1] = 0.       # vowel -> consonant
model.transition_model.unnormalized_transition_matrix[1,0] = 0.       # consonant -> vowel
model.transition_model.unnormalized_transition_matrix[1,1] = -np.inf  # vowel -> vowel
print("Transition matrix:", torch.nn.functional.softmax(model.transition_model.unnormalized_transition_matrix, dim=0))

```

    State priors: tensor([0.6225, 0.3775], device='cuda:0')
    Emission matrix: tensor([[0.0000, 0.0806, 0.0055, 0.0652, 0.0000, 0.0105, 0.0746, 0.0384, 0.0000,
             0.0255, 0.0142, 0.0375, 0.0166, 0.0548, 0.0000, 0.0790, 0.0237, 0.0151,
             0.0629, 0.0349, 0.0000, 0.1072, 0.0155, 0.1230, 0.0579, 0.0574],
            [0.2217, 0.0000, 0.0000, 0.0000, 0.1888, 0.0000, 0.0000, 0.0000, 0.1722,
             0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0870, 0.0000, 0.0000, 0.0000,
             0.0000, 0.0000, 0.3303, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000]],
           device='cuda:0')
    Transition matrix: tensor([[0., 1.],
            [1., 0.]], device='cuda:0')

Try sampling from our hard-coded model:

```
# Sample some outputs
for _ in range(4):
  sampled_x, sampled_z = model.sample(T=5)
  print("x:", decode(sampled_x))
  print("z:", sampled_z)
```

    x: napax
    z: [0, 1, 0, 1, 0]
    x: ipoyo
    z: [1, 0, 1, 0, 1]
    x: upoye
    z: [1, 0, 1, 0, 1]
    x: hihiv
    z: [0, 1, 0, 1, 0]

## The Three Problems

In a [classic tutorial](https://www.cs.cmu.edu/~cga/behavior/rabiner1.pdf) on HMMs, Lawrence Rabiner describes "three problems" that need to be solved before you can effectively use an HMM. They are:
- Problem 1: How do we efficiently compute $p(\mathbf{x})$?
- Problem 2: How do we find the most likely state sequence $\mathbf{z}$ that could have generated the data?
- Problem 3: How do we train the model?

In the rest of the notebook, we will see how to solve each problem and implement the solutions in PyTorch.

### Problem 1: How do we compute $p(\mathbf{x})$?

#### *Why?*
Why might we care about computing $p(\mathbf{x})$? Here's two reasons.
* Given two HMMs, $\theta_1$ and $\theta_2$, we can compute the likelihood of some data $\mathbf{x}$ under each model, $p_{\theta_1}(\mathbf{x})$ and $p_{\theta_2}(\mathbf{x})$, to decide which model is a better fit to the data.

  (For example, given an HMM for English speech and an HMM for French speech, we could compute the likelihood given each model, and pick the model with the higher likelihood to infer whether the person is speaking English or French.)
* Being able to compute $p(\mathbf{x})$ gives us a way to train the model, as we will see later.

#### *How?*
Given that we want $p(\mathbf{x})$, how do we compute it?

We've assumed that the data is generated by visiting some sequence of states $\mathbf{z}$ and picking an output $x_t$ for each $z_t$ from the emission distribution $p(x_t|z_t)$. So if we knew $\mathbf{z}$, then the probability of $\mathbf{x}$ could be computed as follows:

$$p(\mathbf{x}|\mathbf{z}) = \prod_{t} p(x_t|z_t) p(z_t|z_{t-1})$$

However, we don't know $\mathbf{z}$; it's hidden. But we do know the probability of any given $\mathbf{z}$, independent of what we observe. So we could get the probability of $\mathbf{x}$ by summing over the different possibilities for $\mathbf{z}$, like this:

$$p(\mathbf{x}) = \sum_{\mathbf{z}} p(\mathbf{x}|\mathbf{z}) p(\mathbf{z}) = \sum_{\mathbf{z}} \prod_{t} p(x_t|z_t) p(z_t|z_{t-1})$$

The problem is: if you try to take that sum directly, you will need to compute $N^T$ terms. This is impossible to do for anything but very short sequences. For example, let's say the sequence is of length $T=100$ and there are $N=2$ possible states. Then we would need to check $N^T = 2^{100} \approx 10^{30}$ different possible state sequences.

We need a way to compute $p(\mathbf{x})$ that doesn't require us to explicitly calculate all $N^T$ terms. For this, we use the forward algorithm.

________

The Forward Algorithm

> for $s=1 \rightarrow N$:\
>       $\alpha_{s,1} := b_s(x_1) \cdot \pi_s$
>
> for $t = 2 \rightarrow T$:\
>       for $s = 1 \rightarrow N$:\
>
> $\alpha_{s,t} := b_s(x_t) \cdot \underset{s'}{\sum} A_{s, s'} \cdot \alpha_{s',t-1} $
>
> $p(\mathbf{x}) := \underset{s}{\sum} \alpha_{s,T}$\
> return $p(\mathbf{x})$
________

The forward algorithm is much faster than enumerating all $N^T$ possible state sequences: it requires only $O(N^2T)$ operations to run, since each step is mostly multiplying the vector of forward variables by the transition matrix. (And very often we can reduce that complexity even further, if the transition matrix is sparse.)

There is one practical problem with the forward algorithm as presented above: it is prone to underflow due to multiplying a long chain of small numbers, since probabilities are always between 0 and 1. Instead, let's do everything in the log domain. In the log domain, a multiplication becomes a sum, and a sum becomes a [logsumexp](https://lorenlugosch.github.io/posts/2020/06/logsumexp/).

________

The Forward Algorithm (Log Domain)

> for $s=1 \rightarrow N$:\
>       $\text{log }\alpha_{s,1} := \text{log }b_s(x_1) + \text{log }\pi_s$
>
> for $t = 2 \rightarrow T$:\
>       for $s = 1 \rightarrow N$:\
>
> $\text{log }\alpha_{s,t} := \text{log }b_s(x_t) +  \underset{s'}{\text{logsumexp}} \left( \text{log }A_{s, s'} + \text{log }\alpha_{s',t-1} \right)$
>
> $\text{log }p(\mathbf{x}) := \underset{s}{\text{logsumexp}} \left( \text{log }\alpha_{s,T} \right)$\
> return $\text{log }p(\mathbf{x})$
________

Now that we have a numerically stable version of the forward algorithm, let's implement it in PyTorch.

```
def HMM_forward(self, x, T):
  """
  x : IntTensor of shape (batch size, T_max)
  T : IntTensor of shape (batch size)

  Compute log p(x) for each example in the batch.
  T = length of each example
  """
  if self.is_cuda:
  	x = x.cuda()
  	T = T.cuda()

  batch_size = x.shape[0]; T_max = x.shape[1]
  log_state_priors = torch.nn.functional.log_softmax(self.unnormalized_state_priors, dim=0)
  log_alpha = torch.zeros(batch_size, T_max, self.N)
  if self.is_cuda: log_alpha = log_alpha.cuda()

  log_alpha[:, 0, :] = self.emission_model(x[:,0]) + log_state_priors
  for t in range(1, T_max):
    log_alpha[:, t, :] = self.emission_model(x[:,t]) + self.transition_model(log_alpha[:, t-1, :])

  # Select the sum for the final timestep (each x may have different length).
  log_sums = log_alpha.logsumexp(dim=2)
  log_probs = torch.gather(log_sums, 1, T.view(-1,1) - 1)
  return log_probs

def emission_model_forward(self, x_t):
  log_emission_matrix = torch.nn.functional.log_softmax(self.unnormalized_emission_matrix, dim=1)
  out = log_emission_matrix[:, x_t].transpose(0,1)
  return out

def transition_model_forward(self, log_alpha):
  """
  log_alpha : Tensor of shape (batch size, N)
  Multiply previous timestep's alphas by transition matrix (in log domain)
  """
  log_transition_matrix = torch.nn.functional.log_softmax(self.unnormalized_transition_matrix, dim=0)

  # Matrix multiplication in the log domain
  out = log_domain_matmul(log_transition_matrix, log_alpha.transpose(0,1)).transpose(0,1)
  return out

def log_domain_matmul(log_A, log_B):
	"""
	log_A : m x n
	log_B : n x p
	output : m x p matrix

	Normally, a matrix multiplication
	computes out_{i,j} = sum_k A_{i,k} x B_{k,j}

	A log domain matrix multiplication
	computes out_{i,j} = logsumexp_k log_A_{i,k} + log_B_{k,j}
	"""
	m = log_A.shape[0]
	n = log_A.shape[1]
	p = log_B.shape[1]

	# log_A_expanded = torch.stack([log_A] * p, dim=2)
	# log_B_expanded = torch.stack([log_B] * m, dim=0)
    # fix for PyTorch > 1.5 by egaznep on Github:
	log_A_expanded = torch.reshape(log_A, (m,n,1))
	log_B_expanded = torch.reshape(log_B, (1,n,p))

	elementwise_sum = log_A_expanded + log_B_expanded
	out = torch.logsumexp(elementwise_sum, dim=1)

	return out

TransitionModel.forward = transition_model_forward
EmissionModel.forward = emission_model_forward
HMM.forward = HMM_forward
```

Try running the forward algorithm on our vowels/consonants model from before:

```
x = torch.stack( [torch.tensor(encode("cat"))] )
T = torch.tensor([3])
print(model.forward(x, T))

x = torch.stack( [torch.tensor(encode("aba")), torch.tensor(encode("abb"))] )
T = torch.tensor([3,3])
print(model.forward(x, T))
```

    tensor([[-10.5390]], device='cuda:0')
    tensor([[-6.5049],
            [   -inf]], device='cuda:0')

When using the vowel <-> consonant HMM from above, notice that the forward algorithm returns $-\infty$ for $\mathbf{x} = \text{"abb"}$. That's because our transition matrix says the probability of vowel -> vowel and consonant -> consonant is 0, so the probability of $\text{"abb"}$ happening is 0, and thus the log probability is $-\infty$.

#### *Side note: deriving the forward algorithm*

If you're interested in understanding how the forward algorithm actually computes $p(\mathbf{x})$, read this section; if not, skip to the next part on "Problem 2" (finding the most likely state sequence).

To derive the forward algorithm, start by deriving the forward variable:

$$\begin{align}
    \alpha_{s,t} &= p(x_1, x_2, \dots, x_t, z_t=s) \\
     &= p(x_t | x_1, x_2, \dots, x_{t-1}, z_t = s) \cdot p(x_1, x_2, \dots, x_{t-1}, z_t = s)  \\
    &= p(x_t | z_t = s) \cdot p(x_1, x_2, \dots, x_{t-1}, z_t = s) \\
    &= p(x_t | z_t = s) \cdot \left( \sum_{s'} p(x_1, x_2, \dots, x_{t-1}, z_{t-1}=s', z_t = s) \right)\\
    &= p(x_t | z_t = s) \cdot \left( \sum_{s'} p(z_t = s | x_1, x_2, \dots, x_{t-1}, z_{t-1}=s') \cdot p(x_1, x_2, \dots, x_{t-1}, z_{t-1}=s') \right)\\
    &= \underbrace{p(x_t | z_t = s)}_{\text{emission model}} \cdot \left( \sum_{s'} \underbrace{p(z_t = s | z_{t-1}=s')}_{\text{transition model}} \cdot \underbrace{p(x_1, x_2, \dots, x_{t-1}, z_{t-1}=s')}_{\text{forward variable for previous timestep}} \right)\\
    &= b_s(x_t) \cdot \left( \sum_{s'} A_{s, s'} \cdot \alpha_{s',t-1} \right)
    \end{align}$$

I'll explain how to get to each line of this equation from the previous line.

Line 1 is the definition of the forward variable $\alpha_{s,t}$.

Line 2 is the chain rule ($p(A,B) = p(A|B) \cdot p(B)$, where $A$ is $x_t$ and $B$ is all the other variables).

In Line 3, we apply Assumption 2: the probability of observation $x_t$ depends only on the current state $z_t$.

In Line 4, we marginalize over all the possible states in the previous timestep $t-1$.

In Line 5, we apply the chain rule again.

In Line 6, we apply Assumption 1: the current state depends only on the previous state.

In Line 7, we substitute in the emission probability, the transition probability, and the forward variable for the previous timestep, to get the complete recursion.

The formula above can be used for $t = 2 \rightarrow T$. At $t=1$, there is no previous state, so instead of the transition matrix $A$, we use the state priors $\pi$, which tell us the probability of starting in each state. Thus for $t=1$, the forward variables are computed as follows:

$$\begin{align}
\alpha_{s,1} &= p(x_1, z_1=s) \\
  &= p(x_1 | z_1 = s) \cdot p(z_1 = s)  \\
&= b_s(x_1) \cdot \pi_s
\end{align}$$

Finally, to compute $p(\mathbf{x}) = p(x_1, x_2, \dots, x_T)$, we marginalize over $\alpha_{s,T}$, the forward variables computed in the last timestep:

$$\begin{align*}
p(\mathbf{x}) &= \sum_{s} p(x_1, x_2, \dots, x_T, z_T = s) \\
&= \sum_{s} \alpha_{s,T}
\end{align*}$$

You can get from this formulation to the log domain formulation by taking the log of the forward variable, and using these identities:
- $\text{log }(a \cdot b) = \text{log }a + \text{log }b$
- $\text{log }(a + b) = \text{log }(e^{\text{log }a} + e^{\text{log }b}) = \text{logsumexp}(\text{log }a, \text{log }b)$

### Problem 2: How do we compute $\underset{\mathbf{z}}{\text{argmax }} p(\mathbf{z}|\mathbf{x})$?

Given an observation sequence $\mathbf{x}$, we may want to find the most likely sequence of states that could have generated $\mathbf{x}$. (Given the sequence of selfies, we want to infer what cities the friend visited.) In other words, we want $\underset{\mathbf{z}}{\text{argmax }} p(\mathbf{z}|\mathbf{x})$.

We can use Bayes' rule to rewrite this expression:
    $$\begin{align*}
    \underset{\mathbf{z}}{\text{argmax }} p(\mathbf{z}|\mathbf{x}) &= \underset{\mathbf{z}}{\text{argmax }} \frac{p(\mathbf{x}|\mathbf{z}) p(\mathbf{z})}{p(\mathbf{x})} \\
    &= \underset{\mathbf{z}}{\text{argmax }} p(\mathbf{x}|\mathbf{z}) p(\mathbf{z})
    \end{align*}$$

Hmm! That last expression, $\underset{\mathbf{z}}{\text{argmax }} p(\mathbf{x}|\mathbf{z}) p(\mathbf{z})$, looks suspiciously similar to the intractable expression we encountered before introducing the forward algorithm, $\underset{\mathbf{z}}{\sum} p(\mathbf{x}|\mathbf{z}) p(\mathbf{z})$.

And indeed, just as the intractable *sum* over all $\mathbf{z}$ can be implemented efficiently using the forward algorithm, so too this intractable *argmax* can be implemented efficiently using a similar divide-and-conquer algorithm: the legendary Viterbi algorithm!

________

The Viterbi Algorithm

> for $s=1 \rightarrow N$:\
>       $\delta_{s,1} := b_s(x_1) \cdot \pi_s$\
>       $\psi_{s,1} := 0$
>
> for $t = 2 \rightarrow T$:\
>       for $s = 1 \rightarrow N$:\
>             $\delta_{s,t} := b_s(x_t) \cdot \left( \underset{s'}{\text{max }} A_{s, s'} \cdot \delta_{s',t-1} \right)$\
            $\psi_{s,t} := \underset{s'}{\text{argmax }} A_{s, s'} \cdot \delta_{s',t-1}$
>
> $z_T^* := \underset{s}{\text{argmax }} \delta_{s,T}$\
> for $t = T-1 \rightarrow 1$:\
      $z_{t}^* := \psi_{z_{t+1}^*,t+1}$
>
> $\mathbf{z}^* := \{z_{1}^*, \dots, z_{T}^* \}$\
return $\mathbf{z}^*$
________

The Viterbi algorithm looks somewhat gnarlier than the forward algorithm, but it is essentially the same algorithm, with two tweaks: 1) instead of taking the sum over previous states, we take the max; and 2) we record the argmax of the previous states in a table, and loop back over this table at the end to get $\mathbf{z}^*$, the most likely state sequence. (And like the forward algorithm, we should run the Viterbi algorithm in the log domain for better numerical stability.)

Let's add the Viterbi algorithm to our PyTorch model:

```
def viterbi(self, x, T):
  """
  x : IntTensor of shape (batch size, T_max)
  T : IntTensor of shape (batch size)
  Find argmax_z log p(x|z) for each (x) in the batch.
  """
  if self.is_cuda:
    x = x.cuda()
    T = T.cuda()

  batch_size = x.shape[0]; T_max = x.shape[1]
  log_state_priors = torch.nn.functional.log_softmax(self.unnormalized_state_priors, dim=0)
  log_delta = torch.zeros(batch_size, T_max, self.N).float()
  psi = torch.zeros(batch_size, T_max, self.N).long()
  if self.is_cuda:
    log_delta = log_delta.cuda()
    psi = psi.cuda()

  log_delta[:, 0, :] = self.emission_model(x[:,0]) + log_state_priors
  for t in range(1, T_max):
    max_val, argmax_val = self.transition_model.maxmul(log_delta[:, t-1, :])
    log_delta[:, t, :] = self.emission_model(x[:,t]) + max_val
    psi[:, t, :] = argmax_val

  # Get the log probability of the best path
  log_max = log_delta.max(dim=2)[0]
  best_path_scores = torch.gather(log_max, 1, T.view(-1,1) - 1)

  # This next part is a bit tricky to parallelize across the batch,
  # so we will do it separately for each example.
  z_star = []
  for i in range(0, batch_size):
    z_star_i = [ log_delta[i, T[i] - 1, :].max(dim=0)[1].item() ]
    for t in range(T[i] - 1, 0, -1):
      z_t = psi[i, t, z_star_i[0]].item()
      z_star_i.insert(0, z_t)

    z_star.append(z_star_i)

  return z_star, best_path_scores # return both the best path and its log probability

def transition_model_maxmul(self, log_alpha):
  log_transition_matrix = torch.nn.functional.log_softmax(self.unnormalized_transition_matrix, dim=0)

  out1, out2 = maxmul(log_transition_matrix, log_alpha.transpose(0,1))
  return out1.transpose(0,1), out2.transpose(0,1)

def maxmul(log_A, log_B):
	"""
	log_A : m x n
	log_B : n x p
	output : m x p matrix

	Similar to the log domain matrix multiplication,
	this computes out_{i,j} = max_k log_A_{i,k} + log_B_{k,j}
	"""
	m = log_A.shape[0]
	n = log_A.shape[1]
	p = log_B.shape[1]

	log_A_expanded = torch.stack([log_A] * p, dim=2)
	log_B_expanded = torch.stack([log_B] * m, dim=0)

	elementwise_sum = log_A_expanded + log_B_expanded
	out1,out2 = torch.max(elementwise_sum, dim=1)

	return out1,out2

TransitionModel.maxmul = transition_model_maxmul
HMM.viterbi = viterbi
```

Try running Viterbi on an input sequence, given the vowel/consonant HMM:

```
x = torch.stack( [torch.tensor(encode("aba")), torch.tensor(encode("abb"))] )
T = torch.tensor([3,3])
print(model.viterbi(x, T))
```

    ([[1, 0, 1], [1, 0, 0]], tensor([[-6.5049],
            [   -inf]], device='cuda:0'))

For $\mathbf{x} = \text{"aba"}$, the Viterbi algorithm returns $\mathbf{z}^* = \{1,0,1\}$. This corresponds to "vowel, consonant, vowel" according to the way we defined the states above, which is correct for this input sequence. Yay!

For $\mathbf{x} = \text{"abb"}$, the Viterbi algorithm still returns a $\mathbf{z}^*$, but we know this is gibberish because "vowel, consonant, consonant" is impossible under this HMM, and indeed the log probability of this path is $-\infty$.

Let's compare the "forward score" (the log probability of all possible paths, returned by the forward algorithm) with the "Viterbi score" (the log probability of the maximum likelihood path, returned by the Viterbi algorithm):

```
print(model.forward(x, T))
print(model.viterbi(x, T)[1])
```

    tensor([[-6.5049],
            [   -inf]], device='cuda:0')
    tensor([[-6.5049],
            [   -inf]], device='cuda:0')

The two scores are the same! That's because in this instance there is only one possible path through the HMM, so the probability of the most likely path is the same as the sum of the probabilities of all possible paths.

In general, though, the forward score and Viterbi score will always be somewhat close. This is because of a property of the $\text{logsumexp}$ function: $\text{logsumexp}(\mathbf{x}) \approx \max (\mathbf{x})$. ($\text{logsumexp}$ is sometimes referred to as the "smooth maximum" function.)

```
x = torch.tensor([1., 2., 3.])
print(x.max(dim=0)[0])
print(x.logsumexp(dim=0))
```

    tensor(3.)
    tensor(3.4076)

### Problem 3: How do we train the model?

Earlier, we hard-coded an HMM to have certain behavior. What we would like to do instead is have the HMM learn to model the data on its own. And while it is possible to use supervised learning with an HMM (by hard-coding the emission model or the transition model) so that the states have a particular interpretation, the really cool thing about HMMs is that they are naturally unsupervised learners, so they can learn to use their different states to represent different patterns in the data, without the programmer needing to indicate what each state means.

Like many machine learning models, an HMM can be trained using maximum likelihood estimation, i.e.:

$$\theta^* = \underset{\theta}{\text{argmin }} -\sum_{\mathbf{x}^i}\text{log }p_{\theta}(\mathbf{x}^i)$$

where $\mathbf{x}^1, \mathbf{x}^2, \dots$ are training examples.

The standard method for doing this is the Expectation-Maximization (EM) algorithm, which for HMMs is also called the "Baum-Welch" algorithm. In EM training, we alternate between an "E-step", where we estimate the values of the latent variables, and an "M-step", where the model parameters are updated given the estimated latent variables. (Think $k$-means, where you guess which cluster each data point belongs to, then reestimate where the clusters are, and repeat.) The EM algorithm has some nice properties: it is guaranteed at each step to decrease the loss function, and the E-step and M-step may have an exact closed form solution, in which case no pesky learning rates are required.

But because the HMM forward algorithm is differentiable with respect to all the model parameters, we can also just take advantage of automatic differentiation methods in libraries like PyTorch and try to minimize $-\text{log }p_{\theta}(\mathbf{x})$ directly, by backpropagating through the forward algorithm and running stochastic gradient descent. That means we don't need to write any additional HMM code to implement training: `loss.backward()` is all you need.

Here we will implement SGD training for an HMM in PyTorch. First, some helper classes:

```
import torch.utils.data
from collections import Counter
from sklearn.model_selection import train_test_split

class TextDataset(torch.utils.data.Dataset):
  def __init__(self, lines):
    self.lines = lines # list of strings
    collate = Collate() # function for generating a minibatch from strings
    self.loader = torch.utils.data.DataLoader(self, batch_size=1024, num_workers=1, shuffle=True, collate_fn=collate)

  def __len__(self):
    return len(self.lines)

  def __getitem__(self, idx):
    line = self.lines[idx].lstrip(" ").rstrip("\n").rstrip(" ").rstrip("\n")
    return line

class Collate:
  def __init__(self):
    pass

  def __call__(self, batch):
    """
    Returns a minibatch of strings, padded to have the same length.
    """
    x = []
    batch_size = len(batch)
    for index in range(batch_size):
      x_ = batch[index]

      # convert letters to integers
      x.append(encode(x_))

    # pad all sequences with 0 to have same length
    x_lengths = [len(x_) for x_ in x]
    T = max(x_lengths)
    for index in range(batch_size):
      x[index] += [0] * (T - len(x[index]))
      x[index] = torch.tensor(x[index])

    # stack into single tensor
    x = torch.stack(x)
    x_lengths = torch.tensor(x_lengths)
    return (x,x_lengths)
```

Let's load some training/testing data. By default, this will use the unix "words" file, but you could also use your own text file.

```
!wget https://raw.githubusercontent.com/lorenlugosch/pytorch_HMM/master/data/train/training.txt

filename = "training.txt"

with open(filename, "r") as f:
  lines = f.readlines() # each line of lines will have one word

alphabet = list(Counter(("".join(lines))).keys())
train_lines, valid_lines = train_test_split(lines, test_size=0.1, random_state=42)
train_dataset = TextDataset(train_lines)
valid_dataset = TextDataset(valid_lines)

M = len(alphabet)
```

    --2021-03-20 18:38:40--  https://raw.githubusercontent.com/lorenlugosch/pytorch_HMM/master/data/train/training.txt
    Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.111.133, 185.199.110.133, 185.199.108.133, ...
    Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.111.133|:443... connected.
    HTTP request sent, awaiting response... 200 OK
    Length: 2493109 (2.4M) [text/plain]
    Saving to: ‘training.txt’

    training.txt        100%[===================>]   2.38M  --.-KB/s    in 0.02s

    2021-03-20 18:38:40 (102 MB/s) - ‘training.txt’ saved [2493109/2493109]

We will use a Trainer class for training and testing the model:

```
from tqdm import tqdm # for displaying progress bar

class Trainer:
  def __init__(self, model, lr):
    self.model = model
    self.lr = lr
    self.optimizer = torch.optim.Adam(model.parameters(), lr=self.lr, weight_decay=0.00001)

  def train(self, dataset):
    train_loss = 0
    num_samples = 0
    self.model.train()
    print_interval = 50
    for idx, batch in enumerate(tqdm(dataset.loader)):
      x,T = batch
      batch_size = len(x)
      num_samples += batch_size
      log_probs = self.model(x,T)
      loss = -log_probs.mean()
      self.optimizer.zero_grad()
      loss.backward()
      self.optimizer.step()
      train_loss += loss.cpu().data.numpy().item() * batch_size
      if idx % print_interval == 0:
        print("loss:", loss.item())
        for _ in range(5):
          sampled_x, sampled_z = self.model.sample()
          print(decode(sampled_x))
          print(sampled_z)
    train_loss /= num_samples
    return train_loss

  def test(self, dataset):
    test_loss = 0
    num_samples = 0
    self.model.eval()
    print_interval = 50
    for idx, batch in enumerate(dataset.loader):
      x,T = batch
      batch_size = len(x)
      num_samples += batch_size
      log_probs = self.model(x,T)
      loss = -log_probs.mean()
      test_loss += loss.cpu().data.numpy().item() * batch_size
      if idx % print_interval == 0:
        print("loss:", loss.item())
        sampled_x, sampled_z = self.model.sample()
        print(decode(sampled_x))
        print(sampled_z)
    test_loss /= num_samples
    return test_loss
```

Finally, initialize the model and run the main training loop. Every 50 batches, the code will produce a few samples from the model. Over time, these samples should look more and more realistic.

```
# Initialize model
model = HMM(N=64, M=M)

# Train the model
num_epochs = 10
trainer = Trainer(model, lr=0.01)

for epoch in range(num_epochs):
        print("========= Epoch %d of %d =========" % (epoch+1, num_epochs))
        train_loss = trainer.train(train_dataset)
        valid_loss = trainer.test(valid_dataset)

        print("========= Results: epoch %d of %d =========" % (epoch+1, num_epochs))
        print("train loss: %.2f| valid loss: %.2f\n" % (train_loss, valid_loss) )
```

      0%|          | 0/208 [00:00<?, ?it/s]

    ========= Epoch 1 of 10 =========

      1%|▏         | 3/208 [00:00<00:49,  4.10it/s]

    loss: 38.27830505371094
    pXTePbVjYF
    [41, 61, 20, 23, 1, 29, 18, 14, 24, 24]
    LuunvHIuqX
    [56, 36, 38, 49, 19, 2, 23, 45, 4, 3]
    bYhujZXBL

    [55, 55, 49, 39, 4, 15, 57, 23, 52, 53]
    FdUCylApst
    [34, 40, 36, 27, 26, 44, 53, 56, 26, 46]
    FtyJoeDVk

    [34, 23, 20, 61, 6, 51, 8, 13, 34, 26]

     25%|██▌       | 53/208 [00:03<00:10, 14.48it/s]

    loss: 33.30974578857422
    lTsYD
    ntNj
    [34, 18, 44, 31, 39, 60, 21, 19, 10, 19]
    gwgHosQkqc
    [34, 31, 59, 19, 45, 4, 13, 63, 28, 10]
    sImtUHnn
    e
    [6, 28, 37, 45, 27, 56, 38, 3, 9, 54]
    rrgClNlKsr
    [43, 49, 15, 12, 45, 1, 44, 53, 2, 63]
    eXaPznhikV
    [41, 42, 12, 51, 14, 1, 41, 37, 43, 15]

     50%|████▉     | 103/208 [00:07<00:07, 14.90it/s]

    loss: 30.279699325561523
    VdostoateO
    [11, 0, 12, 14, 19, 28, 23, 62, 43, 60]
    siiAilJnXc
    [37, 52, 19, 37, 54, 44, 43, 48, 21, 61]
    moeddnaoyw
    [44, 14, 21, 37, 37, 45, 54, 50, 14, 31]
    ltp-iangtI
    [56, 14, 30, 9, 45, 54, 11, 15, 16, 19]
    mjqratgtpr
    [37, 61, 55, 49, 29, 48, 44, 35, 62, 44]

     74%|███████▎  | 153/208 [00:10<00:03, 14.67it/s]

    loss: 28.56381607055664
    oropeudous
    [45, 14, 52, 56, 52, 49, 37, 52, 44, 14]
    bltfbwikte
    [56, 29, 13, 42, 38, 53, 61, 51, 14, 52]
    TnDomoiibo
    [19, 21, 45, 44, 44, 53, 61, 24, 56, 59]
    niisehoLtL
    [38, 54, 19, 60, 50, 49, 39, 6, 23, 52]
    cstoeGebec
    [33, 54, 23, 52, 29, 13, 52, 56, 52, 45]

     98%|█████████▊| 203/208 [00:13<00:00, 14.73it/s]

    loss: 26.615825653076172
    -ibBiNplii
    [25, 61, 60, 23, 61, 60, 56, 49, 61, 56]
    eKteaeraei
    [8, 44, 23, 50, 21, 50, 37, 52, 56, 59]
    mafkfibjta
    [20, 29, 35, 57, 20, 52, 56, 52, 62, 29]
    unJhevRlcu
    [42, 21, 48, 9, 61, 40, 50, 14, 45, 39]
    uoryatidol
    [34, 44, 14, 61, 29, 23, 61, 48, 28, 58]

    100%|██████████| 208/208 [00:13<00:00, 14.91it/s]

    loss: 26.30190658569336
    wusstetiNr
    [25, 39, 60, 32, 23, 52, 18, 59, 24, 45]

      0%|          | 0/208 [00:00<?, ?it/s]

    ========= Results: epoch 1 of 10 =========
    train loss: 30.75| valid loss: 26.34

    ========= Epoch 2 of 10 =========

      1%|▏         | 3/208 [00:00<00:44,  4.58it/s]

    loss: 26.122982025146484
    undaiqirii
    [42, 21, 48, 14, 59, 14, 59, 14, 59, 19]
    rtpsernaim
    [56, 14, 61, 32, 13, 42, 21, 48, 59, 37]
    oedsKinide
    [1, 52, 35, 54, 16, 61, 21, 61, 48, 50]
    cydeneison
    [48, 52, 40, 50, 21, 52, 19, 32, 59, 21]
    dusttMlyet
    [31, 39, 60, 23, 45, 63, 43, 14, 52, 23]

     25%|██▌       | 53/208 [00:03<00:10, 14.94it/s]

    loss: 25.615436553955078
    bedisYmasu
    [37, 50, 37, 61, 60, 32, 33, 29, 45, 39]
    hiSncratrb
    [9, 59, 47, 21, 11, 49, 29, 23, 35, 53]
    pricuuriss
    [56, 9, 19, 60, 34, 39, 37, 19, 60, 32]
    Loiptikenb
    [12, 52, 54, 3, 23, 61, 48, 50, 21, 27]
    carcomaepo
    [11, 59, 21, 37, 52, 60, 23, 52, 56, 59]

     50%|████▉     | 103/208 [00:06<00:06, 15.11it/s]

    loss: 24.506874084472656
    untirtinra
    [42, 21, 48, 19, 21, 48, 61, 11, 9, 29]
    macdestior
    [20, 29, 35, 48, 50, 43, 48, 19, 45, 21]
    dptodingis
    [37, 3, 23, 52, 48, 19, 21, 22, 61, 60]
    pdliseenno
    [56, 44, 53, 61, 60, 32, 50, 43, 21, 52]
    urLlhsumil
    [42, 21, 61, 48, 9, 31, 39, 37, 61, 58]

     74%|███████▎  | 153/208 [00:10<00:03, 14.25it/s]

    loss: 24.405460357666016
    inthtemlis
    [42, 21, 48, 49, 45, 50, 37, 17, 61, 60]
    rterideran
    [14, 8, 52, 37, 61, 48, 50, 14, 29, 21]
    ipimufferu
    [19, 12, 59, 37, 61, 58, 57, 52, 14, 61]
    pracansing
    [56, 14, 52, 34, 54, 43, 32, 19, 21, 48]
    sermyssuae
    [56, 50, 43, 37, 61, 60, 31, 39, 14, 52]

     98%|█████████▊| 203/208 [00:13<00:00, 14.90it/s]

    loss: 24.571157455444336
    diniainiWs
    [48, 61, 56, 61, 29, 35, 48, 61, 60, 32]
    rydepreken
    [14, 52, 48, 52, 56, 14, 52, 22, 50, 21]
    catheallon
    [11, 29, 23, 9, 59, 29, 35, 53, 52, 21]
    dusmotiona
    [31, 39, 60, 23, 59, 23, 19, 45, 21, 54]
    teagenybaa
    [56, 59, 29, 26, 50, 14, 52, 56, 29, 19]

    100%|██████████| 208/208 [00:13<00:00, 15.03it/s]

    loss: 24.482282638549805
    parsealogi
    [56, 50, 21, 23, 52, 29, 53, 52, 22, 61]

      0%|          | 0/208 [00:00<?, ?it/s]

    ========= Results: epoch 2 of 10 =========
    train loss: 25.03| valid loss: 24.38

    ========= Epoch 3 of 10 =========

      1%|▏         | 3/208 [00:00<00:43,  4.69it/s]

    loss: 24.47772216796875
    Didanidive
    [12, 19, 48, 59, 37, 61, 48, 61, 40, 50]
    ledspEulli
    [56, 50, 21, 60, 32, 39, 39, 3, 53, 61]
    setontetil
    [20, 59, 23, 59, 21, 48, 50, 23, 61, 21]
    croosxaunc
    [56, 14, 45, 39, 60, 23, 59, 42, 21, 11]
    phoousyycf
    [56, 9, 52, 45, 39, 60, 9, 52, 11, 62]

     25%|██▌       | 53/208 [00:03<00:10, 14.75it/s]

    loss: 23.98973274230957
    megleraldh
    [20, 52, 22, 53, 52, 14, 29, 35, 48, 9]
    unrphygnRt
    [42, 21, 43, 32, 9, 52, 22, 53, 61, 58]
    urtiatudic
    [42, 21, 23, 61, 29, 23, 59, 37, 61, 11]
    aochantere
    [37, 52, 11, 9, 59, 21, 48, 50, 21, 42]
    apkhyonvTn
    [54, 3, 23, 9, 52, 59, 21, 40, 50, 53]

     50%|████▉     | 103/208 [00:07<00:07, 14.89it/s]

    loss: 23.897340774536133
    shybinponm
    [60, 33, 52, 48, 61, 21, 56, 52, 21, 32]
    sulneraaer
    [31, 39, 35, 53, 50, 14, 29, 23, 50, 14]
    retomegero
    [14, 52, 23, 50, 14, 52, 22, 50, 14, 59]
    peiardhema
    [56, 49, 61, 29, 21, 48, 9, 50, 37, 29]
    tigintinte
    [56, 61, 40, 19, 21, 23, 61, 21, 48, 50]

     74%|███████▎  | 153/208 [00:10<00:03, 14.40it/s]

    loss: 23.973764419555664
    ctotatovat
    [11, 23, 59, 37, 29, 23, 45, 40, 29, 23]
    Bigindoric
    [25, 19, 48, 19, 21, 48, 52, 37, 61, 11]
    prombejcer
    [56, 14, 52, 37, 16, 50, 43, 32, 59, 21]
    diwuedrase
    [20, 59, 37, 56, 52, 44, 14, 29, 60, 50]
    entamitppa
    [42, 21, 23, 29, 37, 19, 48, 3, 56, 29]

     98%|█████████▊| 203/208 [00:13<00:00, 14.87it/s]

    loss: 23.922351837158203
    sfolycannu
    [54, 58, 59, 53, 52, 11, 29, 21, 48, 50]
    Barantiang
    [20, 52, 37, 29, 21, 23, 61, 29, 21, 22]
    unovemaler
    [42, 21, 52, 40, 50, 37, 29, 23, 50, 14]
    lonquactid
    [20, 59, 21, 13, 36, 29, 60, 23, 61, 48]
    testicarto
    [56, 52, 60, 23, 61, 11, 29, 21, 11, 59]

    100%|██████████| 208/208 [00:14<00:00, 14.80it/s]

    loss: 24.101062774658203
    porgupettm
    [56, 59, 21, 22, 39, 56, 50, 23, 23, 15]

      0%|          | 0/208 [00:00<?, ?it/s]

    ========= Results: epoch 3 of 10 =========
    train loss: 24.04| valid loss: 23.87

    ========= Epoch 4 of 10 =========

      1%|▏         | 3/208 [00:00<00:48,  4.20it/s]

    loss: 23.310888290405273
    sitelarves
    [37, 61, 48, 50, 35, 29, 43, 40, 50, 14]
    froscerseo
    [25, 49, 54, 60, 32, 50, 43, 60, 32, 59]
    docegellor
    [20, 19, 48, 52, 22, 50, 35, 53, 50, 14]
    slrAsancol
    [60, 23, 49, 54, 48, 29, 21, 11, 59, 53]
    oantassush
    [20, 29, 21, 23, 29, 60, 31, 39, 60, 9]

     25%|██▌       | 53/208 [00:03<00:10, 14.20it/s]

    loss: 23.963918685913086
    wymanecean
    [34, 52, 37, 29, 48, 52, 23, 61, 29, 21]
    Chuhcstele
    [12, 9, 52, 33, 52, 60, 23, 50, 14, 52]
    rewmencuPm
    [37, 50, 43, 37, 50, 21, 11, 39, 15, 37]
    uneatwoGui
    [42, 21, 52, 29, 23, 49, 54, 13, 36, 19]
    burslemere
    [20, 39, 43, 60, 53, 52, 37, 50, 14, 52]

     50%|████▉     | 103/208 [00:07<00:07, 14.88it/s]

    loss: 23.50936508178711
    manerbened
    [20, 29, 21, 50, 43, 16, 59, 37, 50, 44]
    agdricalos
    [54, 26, 22, 49, 61, 11, 29, 53, 52, 60]
    utcantedra
    [42, 21, 11, 59, 21, 23, 52, 22, 49, 29]
    honctermis
    [20, 59, 21, 11, 23, 50, 43, 37, 19, 60]
    rymichagat
    [14, 52, 37, 61, 11, 9, 29, 22, 50, 23]

     74%|███████▎  | 153/208 [00:10<00:03, 14.39it/s]

    loss: 23.392898559570312
    rysgastang
    [14, 52, 60, 17, 29, 60, 23, 29, 21, 22]
    aswcereeri
    [54, 60, 61, 48, 50, 14, 52, 50, 14, 61]
    tawwleunol
    [56, 29, 60, 32, 53, 52, 27, 48, 29, 35]
    mepcormian
    [20, 52, 3, 56, 59, 43, 32, 61, 29, 21]
    ctatiskati
    [11, 23, 29, 23, 61, 60, 32, 29, 23, 61]

     98%|█████████▊| 203/208 [00:13<00:00, 14.38it/s]

    loss: 23.561634063720703
    lmnoloulad
    [42, 15, 37, 59, 14, 45, 39, 35, 29, 48]
    fueiyloesi
    [31, 39, 43, 51, 52, 22, 52, 54, 60, 61]
    chertratra
    [11, 9, 50, 43, 23, 14, 29, 23, 49, 54]
    hyacrepage
    [33, 52, 29, 11, 14, 52, 56, 29, 22, 50]
    opphertetn
    [54, 3, 3, 9, 52, 21, 23, 61, 23, 21]

    100%|██████████| 208/208 [00:14<00:00, 14.78it/s]

    loss: 23.406665802001953
    antetepyry
    [42, 21, 48, 52, 11, 52, 3, 52, 14, 52]

      0%|          | 0/208 [00:00<?, ?it/s]

    ========= Results: epoch 4 of 10 =========
    train loss: 23.72| valid loss: 23.66

    ========= Epoch 5 of 10 =========

      1%|▏         | 3/208 [00:00<00:44,  4.62it/s]

    loss: 23.822376251220703
    Tuwurarixa
    [20, 59, 37, 59, 37, 29, 43, 19, 48, 29]
    neritelat-
    [20, 50, 43, 19, 48, 50, 35, 29, 23, 29]
    Tiantfwhlo
    [20, 19, 29, 21, 11, 57, 12, 9, 53, 52]
    Malloeshoc
    [20, 29, 35, 53, 52, 54, 60, 9, 52, 11]
    dolalasten
    [20, 59, 14, 52, 53, 52, 60, 23, 50, 21]

     25%|██▌       | 53/208 [00:03<00:10, 14.70it/s]

    loss: 23.547645568847656
    Phyfloquia
    [12, 9, 52, 22, 53, 52, 13, 36, 19, 29]
    ectantiTat
    [54, 11, 23, 59, 21, 23, 61, 48, 29, 23]
    odlustannc
    [54, 27, 14, 52, 60, 23, 29, 21, 21, 11]
    acaryreidl
    [54, 11, 59, 14, 52, 37, 61, 21, 22, 53]
    ratcethell
    [14, 52, 60, 23, 50, 23, 9, 52, 35, 53]

     50%|████▉     | 103/208 [00:07<00:07, 14.27it/s]

    loss: 23.812715530395508
    trLceungop
    [56, 14, 61, 11, 52, 42, 21, 22, 59, 3]
    aperkishys
    [54, 3, 50, 43, 57, 19, 60, 9, 52, 60]
    septhwoxig
    [20, 59, 3, 23, 9, 0, 59, 37, 61, 26]
    zorantsore
    [20, 59, 14, 29, 21, 60, 32, 59, 43, 50]
    dofleniaba
    [20, 52, 62, 53, 52, 37, 19, 29, 38, 59]

     74%|███████▎  | 153/208 [00:10<00:03, 14.17it/s]

    loss: 23.58541488647461
    quiablarai
    [13, 36, 19, 29, 38, 53, 29, 43, 29, 7]
    ranteiishu
    [31, 42, 21, 23, 50, 35, 19, 60, 9, 59]
    hidlopenad
    [33, 52, 44, 53, 52, 56, 50, 21, 54, 44]
    acovagungn
    [54, 11, 59, 40, 29, 28, 42, 21, 22, 53]
    poplyissou
    [56, 59, 3, 53, 52, 19, 60, 32, 45, 39]

     98%|█████████▊| 203/208 [00:13<00:00, 14.30it/s]

    loss: 23.362699508666992
    eutigxisth
    [54, 27, 23, 61, 26, 37, 19, 60, 23, 9]
    wivyrocyll
    [20, 61, 40, 50, 14, 29, 11, 7, 35, 35]
    purrlescer
    [56, 39, 43, 22, 53, 52, 60, 23, 50, 43]
    sweridater
    [31, 0, 59, 43, 19, 48, 29, 23, 50, 43]
    herystindy
    [33, 50, 14, 52, 60, 23, 61, 21, 48, 52]

    100%|██████████| 208/208 [00:14<00:00, 14.79it/s]

    loss: 23.546817779541016
    susmleptya
    [31, 39, 60, 32, 53, 52, 3, 23, 52, 54]

      0%|          | 0/208 [00:00<?, ?it/s]

    ========= Results: epoch 5 of 10 =========
    train loss: 23.55| valid loss: 23.53

    ========= Epoch 6 of 10 =========

      1%|▏         | 3/208 [00:00<00:46,  4.41it/s]

    loss: 23.335289001464844
    iiayischyr
    [41, 19, 29, 52, 19, 60, 11, 9, 52, 14]
    tesishepry
    [20, 54, 60, 19, 60, 9, 52, 56, 14, 52]
    upryrechni
    [42, 56, 14, 52, 14, 52, 11, 9, 37, 19]
    wonerpgaza
    [20, 59, 37, 50, 43, 3, 17, 29, 48, 29]
    untumunamb
    [42, 21, 23, 27, 18, 42, 21, 29, 15, 16]

     25%|██▌       | 53/208 [00:03<00:10, 14.13it/s]

    loss: 23.553653717041016
    snesichils
    [31, 53, 52, 60, 19, 23, 9, 7, 35, 37]
    shilispern
    [60, 9, 7, 35, 19, 60, 32, 50, 43, 37]
    suwestiorv
    [31, 27, 37, 52, 60, 23, 61, 59, 43, 40]
    atolnetull
    [29, 23, 59, 35, 53, 52, 23, 39, 35, 53]
    coregueten
    [20, 59, 14, 52, 22, 36, 19, 48, 50, 21]

     50%|████▉     | 103/208 [00:07<00:07, 14.26it/s]

    loss: 23.50783920288086
    psouscater
    [56, 14, 45, 39, 60, 23, 29, 23, 50, 14]
    soriirousq
    [20, 59, 37, 19, 47, 14, 45, 39, 60, 13]
    lalotiosat
    [34, 29, 35, 29, 23, 61, 59, 37, 52, 23]
    chooguaxti
    [11, 9, 59, 59, 26, 36, 29, 21, 23, 61]
    Caubeliric
    [20, 29, 27, 37, 29, 35, 19, 14, 61, 41]

     74%|███████▎  | 153/208 [00:10<00:03, 14.69it/s]

    loss: 23.355899810791016
    mutedpundi
    [20, 27, 23, 50, 44, 41, 42, 21, 48, 19]
    unresepent
    [42, 21, 14, 52, 60, 52, 3, 50, 21, 48]
    potedlebro
    [56, 52, 23, 50, 44, 53, 52, 55, 49, 59]
    mesconerad
    [20, 19, 60, 23, 61, 37, 59, 43, 29, 22]
    prangecrys
    [56, 14, 29, 21, 22, 52, 11, 14, 52, 37]

     98%|█████████▊| 203/208 [00:13<00:00, 14.34it/s]

    loss: 23.536277770996094
    Antrianges
    [42, 21, 23, 49, 19, 29, 21, 22, 52, 60]
    dosmidoner
    [20, 52, 60, 32, 19, 48, 50, 21, 54, 43]
    tryloblegi
    [25, 49, 52, 53, 52, 55, 49, 54, 11, 19]
    slyopowert
    [31, 53, 52, 54, 3, 52, 0, 50, 43, 23]
    lamorlossw
    [20, 52, 37, 59, 43, 14, 52, 60, 32, 0]

    100%|██████████| 208/208 [00:14<00:00, 14.80it/s]

    loss: 23.495555877685547
    screjurmic
    [31, 11, 14, 52, 10, 27, 14, 37, 19, 48]

      0%|          | 0/208 [00:00<?, ?it/s]

    ========= Results: epoch 6 of 10 =========
    train loss: 23.44| valid loss: 23.43

    ========= Epoch 7 of 10 =========

      1%|▏         | 3/208 [00:00<00:44,  4.58it/s]

    loss: 23.401981353759766
    catrourequ
    [20, 29, 23, 49, 54, 27, 14, 52, 13, 36]
    Exalistife
    [42, 21, 29, 35, 19, 60, 23, 61, 58, 50]
    ivenitiora
    [54, 40, 50, 21, 19, 23, 61, 59, 37, 29]
    micaramaJi
    [20, 61, 11, 29, 43, 29, 37, 29, 58, 19]
    bydionatea
    [51, 50, 44, 61, 59, 21, 19, 48, 52, 54]

     25%|██▌       | 53/208 [00:03<00:10, 14.46it/s]

    loss: 23.47461700439453
    cophoninyw
    [11, 59, 3, 9, 59, 37, 19, 48, 52, 0]
    plergidedi
    [56, 14, 52, 21, 22, 19, 48, 50, 44, 19]
    demorcicon
    [20, 52, 37, 59, 43, 23, 61, 11, 59, 37]
    sephontedo
    [31, 52, 60, 9, 59, 21, 23, 50, 44, 59]
    chenkethio
    [11, 33, 50, 21, 57, 50, 23, 9, 61, 29]

     50%|████▉     | 103/208 [00:07<00:07, 14.96it/s]

    loss: 22.983810424804688
    spuclyytoa
    [31, 56, 52, 22, 53, 52, 52, 23, 59, 59]
    ingompeliz
    [42, 21, 22, 59, 15, 56, 50, 35, 19, 48]
    rodderlive
    [49, 54, 44, 22, 50, 43, 53, 61, 40, 50]
    molintorct
    [20, 54, 35, 19, 21, 23, 59, 43, 11, 23]
    chonelanis
    [12, 9, 61, 53, 52, 53, 52, 37, 19, 48]

     74%|███████▎  | 153/208 [00:10<00:03, 14.76it/s]

    loss: 23.47952651977539
    luloitmena
    [20, 7, 35, 45, 19, 60, 18, 50, 21, 29]
    dedaificke
    [20, 52, 37, 29, 19, 58, 61, 11, 57, 50]
    anititivea
    [42, 21, 61, 48, 19, 48, 52, 40, 50, 29]
    cuslictfun
    [11, 39, 32, 53, 61, 11, 23, 41, 42, 21]
    helatiplud
    [20, 54, 35, 29, 23, 61, 3, 53, 52, 37]

     98%|█████████▊| 203/208 [00:13<00:00, 14.76it/s]

    loss: 23.140419006347656
    bralomagei
    [55, 49, 54, 35, 45, 37, 29, 1, 52, 19]
    Erydnyrhic
    [25, 14, 52, 44, 53, 17, 12, 9, 61, 11]
    ZaculllVoh
    [20, 59, 11, 39, 35, 35, 53, 6, 59, 33]
    trumyerlip
    [56, 14, 39, 15, 17, 50, 43, 53, 61, 3]
    ruitampolr
    [13, 36, 19, 56, 29, 15, 3, 59, 35, 53]

    100%|██████████| 208/208 [00:14<00:00, 14.83it/s]

    loss: 23.1785945892334
    ovinarmege
    [54, 40, 19, 48, 29, 43, 37, 29, 22, 52]

      0%|          | 0/208 [00:00<?, ?it/s]

    ========= Results: epoch 7 of 10 =========
    train loss: 23.35| valid loss: 23.35

    ========= Epoch 8 of 10 =========

      1%|▏         | 3/208 [00:00<00:45,  4.53it/s]

    loss: 23.04974365234375
    daSytatana
    [20, 59, 53, 52, 56, 29, 48, 29, 21, 29]
    indosetckg
    [42, 21, 44, 59, 31, 52, 60, 11, 57, 1]
    knitervers
    [42, 21, 19, 48, 50, 43, 40, 50, 43, 32]
    sulHberian
    [31, 39, 35, 19, 47, 50, 43, 19, 29, 21]
    meaphiUant
    [20, 52, 54, 3, 9, 61, 37, 59, 21, 23]

     25%|██▌       | 53/208 [00:03<00:10, 14.32it/s]

    loss: 23.460845947265625
    bratsandew
    [55, 49, 29, 23, 32, 29, 21, 22, 52, 56]
    jonOthosse
    [20, 59, 37, 29, 23, 9, 52, 60, 32, 52]
    Tewaelvere
    [20, 52, 0, 29, 50, 35, 40, 50, 43, 50]
    panventebo
    [56, 29, 21, 40, 50, 21, 23, 50, 38, 59]
    calllccink
    [20, 29, 35, 35, 35, 11, 11, 19, 21, 57]

     50%|████▉     | 103/208 [00:07<00:07, 14.11it/s]

    loss: 23.10556411743164
    Sinecogles
    [20, 61, 37, 19, 48, 52, 22, 53, 52, 60]
    wakundenth
    [34, 29, 28, 42, 21, 48, 52, 21, 23, 33]
    sproctinse
    [31, 56, 49, 54, 11, 23, 61, 21, 32, 50]
    spereniogr
    [31, 56, 50, 14, 52, 37, 19, 29, 1, 43]
    semalalatr
    [31, 54, 37, 29, 35, 29, 35, 29, 23, 49]

     74%|███████▎  | 153/208 [00:10<00:03, 13.99it/s]

    loss: 22.967063903808594
    epoulodyat
    [54, 3, 45, 39, 35, 45, 48, 17, 29, 23]
    ebssernaer
    [54, 16, 60, 23, 50, 43, 37, 29, 52, 14]
    Meascomuch
    [20, 52, 54, 60, 23, 45, 18, 27, 11, 9]
    cromicenon
    [11, 49, 59, 37, 19, 48, 52, 37, 59, 37]
    dialddfula
    [20, 19, 29, 35, 44, 44, 62, 39, 35, 29]

     98%|█████████▊| 203/208 [00:13<00:00, 14.81it/s]

    loss: 23.592716217041016
    cipulperdc
    [20, 61, 41, 42, 21, 56, 59, 43, 44, 11]
    suloiansfr
    [31, 39, 35, 45, 19, 29, 21, 32, 25, 14]
    pwivuryssi
    [56, 0, 61, 40, 7, 14, 52, 60, 32, 61]
    damemoitab
    [20, 29, 37, 52, 15, 45, 19, 48, 29, 38]
    porerthomn
    [3, 59, 43, 50, 43, 12, 9, 59, 37, 53]

    100%|██████████| 208/208 [00:14<00:00, 14.75it/s]

    loss: 23.200260162353516
    sulinosser
    [31, 39, 35, 19, 21, 52, 60, 32, 50, 43]

      0%|          | 0/208 [00:00<?, ?it/s]

    ========= Results: epoch 8 of 10 =========
    train loss: 23.29| valid loss: 23.29

    ========= Epoch 9 of 10 =========

      1%|▏         | 3/208 [00:00<00:44,  4.64it/s]

    loss: 23.086050033569336
    seatuedasi
    [31, 52, 29, 23, 36, 52, 44, 59, 37, 19]
    lalocolice
    [20, 54, 35, 59, 11, 59, 35, 19, 48, 52]
    inverlesca
    [42, 21, 40, 50, 43, 53, 52, 60, 11, 29]
    donctabyli
    [20, 59, 21, 11, 23, 29, 38, 7, 35, 19]
    tonneoomme
    [56, 59, 21, 53, 52, 54, 7, 15, 18, 50]

     25%|██▌       | 53/208 [00:03<00:10, 14.31it/s]

    loss: 23.360929489135742
    serptoucka
    [31, 29, 43, 3, 23, 45, 39, 11, 57, 29]
    dmediPineb
    [22, 18, 50, 44, 61, 37, 61, 37, 29, 38]
    tensushest
    [56, 50, 21, 31, 39, 32, 9, 52, 60, 56]
    coreatimor
    [20, 59, 37, 52, 29, 23, 61, 37, 59, 43]
    gAplomalin
    [20, 54, 3, 53, 52, 18, 29, 35, 19, 21]

     50%|████▉     | 103/208 [00:07<00:07, 14.35it/s]

    loss: 23.229515075683594
    dommizerox
    [20, 7, 15, 18, 19, 48, 50, 43, 45, 22]
    chinckirio
    [12, 9, 19, 21, 11, 57, 7, 43, 19, 45]
    ingidobign
    [42, 21, 22, 19, 48, 52, 8, 61, 26, 37]
    Inchapentr
    [42, 21, 11, 9, 29, 3, 52, 21, 23, 14]
    corvoxtita
    [20, 59, 43, 40, 59, 21, 23, 61, 48, 29]

     74%|███████▎  | 153/208 [00:10<00:03, 14.94it/s]

    loss: 23.115970611572266
    shatengmal
    [12, 9, 29, 23, 50, 21, 22, 18, 59, 53]
    agerablecs
    [54, 26, 50, 43, 29, 38, 53, 52, 60, 32]
    bettinnalp
    [8, 52, 23, 23, 61, 48, 37, 29, 35, 3]
    arvervedri
    [54, 43, 40, 50, 43, 40, 50, 44, 14, 61]
    satiltiont
    [31, 29, 23, 7, 35, 23, 61, 59, 21, 23]

     98%|█████████▊| 203/208 [00:13<00:00, 14.14it/s]

    loss: 23.269947052001953
    Mutrinesti
    [20, 27, 23, 49, 61, 37, 52, 60, 23, 61]
    Miatoguian
    [20, 19, 29, 11, 45, 13, 36, 19, 29, 21]
    nisherpher
    [20, 19, 60, 9, 29, 43, 12, 9, 7, 14]
    sUquuspedu
    [31, 54, 13, 36, 52, 60, 32, 50, 44, 27]
    peneclerbo
    [56, 52, 37, 52, 11, 53, 50, 43, 24, 59]

    100%|██████████| 208/208 [00:14<00:00, 14.83it/s]

    loss: 23.198766708374023
    unvealiayt
    [42, 21, 40, 50, 29, 35, 19, 29, 52, 23]

      0%|          | 0/208 [00:00<?, ?it/s]

    ========= Results: epoch 9 of 10 =========
    train loss: 23.22| valid loss: 23.23

    ========= Epoch 10 of 10 =========

      1%|▏         | 3/208 [00:00<00:43,  4.69it/s]

    loss: 23.117088317871094
    dorinestou
    [20, 59, 43, 19, 21, 52, 60, 23, 45, 39]
    bravicahle
    [55, 49, 54, 40, 61, 11, 29, 9, 53, 52]
    purymymier
    [56, 39, 43, 17, 15, 17, 18, 19, 50, 43]
    policanint
    [56, 7, 35, 19, 48, 29, 37, 19, 21, 23]
    amumommvyo
    [54, 15, 39, 37, 59, 15, 18, 40, 50, 45]

     25%|██▌       | 53/208 [00:03<00:11, 13.94it/s]

    loss: 23.243858337402344
    emephonema
    [54, 37, 52, 3, 9, 54, 37, 52, 18, 29]
    chesmalcil
    [12, 9, 52, 60, 18, 29, 35, 11, 7, 35]
    dessatatry
    [20, 52, 60, 32, 29, 23, 29, 23, 14, 52]
    entionimir
    [42, 21, 23, 61, 59, 37, 19, 37, 50, 43]
    Mutistilet
    [20, 27, 23, 61, 60, 23, 61, 53, 52, 23]

     50%|████▉     | 103/208 [00:07<00:07, 14.42it/s]

    loss: 22.98015022277832
    cessiconri
    [20, 52, 60, 32, 61, 11, 59, 21, 14, 19]
    suslollmat
    [31, 39, 32, 53, 52, 35, 35, 18, 29, 23]
    ouretiomed
    [54, 27, 14, 52, 23, 61, 59, 37, 50, 44]
    aptsechere
    [54, 3, 23, 31, 52, 11, 9, 50, 14, 52]
    averebopar
    [54, 40, 50, 14, 52, 24, 59, 3, 29, 43]

     74%|███████▎  | 153/208 [00:10<00:03, 14.57it/s]

    loss: 23.266876220703125
    unzesticed
    [42, 21, 48, 52, 60, 23, 61, 48, 52, 37]
    Ninglulemi
    [20, 19, 21, 22, 49, 27, 14, 52, 18, 19]
    hipanveseg
    [20, 19, 48, 29, 21, 40, 50, 14, 52, 34]
    inpertheco
    [42, 21, 32, 50, 43, 23, 33, 52, 11, 49]
    hequalicec
    [33, 52, 13, 36, 29, 35, 19, 11, 52, 11]

     98%|█████████▊| 203/208 [00:13<00:00, 14.69it/s]

    loss: 23.194381713867188
    jeassisico
    [20, 52, 54, 60, 32, 61, 37, 19, 11, 59]
    brouroster
    [55, 49, 54, 27, 14, 45, 31, 56, 50, 43]
    guaBerinal
    [13, 36, 29, 23, 50, 43, 19, 48, 29, 35]
    nerigesoch
    [20, 50, 43, 19, 1, 52, 60, 59, 11, 9]
    bricoyatre
    [55, 49, 61, 11, 59, 37, 29, 23, 14, 52]

    100%|██████████| 208/208 [00:13<00:00, 14.90it/s]

    loss: 23.0813045501709
    dafletinte
    [20, 54, 58, 53, 52, 23, 61, 21, 23, 50]
    ========= Results: epoch 10 of 10 =========
    train loss: 23.18| valid loss: 23.19

You may wish to try different values of $N$ and see what the impact on sample quality is.

```
x = torch.tensor(encode("quack")).unsqueeze(0)
T = torch.tensor([5])
print(model.viterbi(x,T))

x = torch.tensor(encode("quick")).unsqueeze(0)
T = torch.tensor([5])
print(model.viterbi(x,T))

x = torch.tensor(encode("qurck")).unsqueeze(0)
T = torch.tensor([5])
print(model.viterbi(x,T)) # should have lower probability---in English only vowels follow "qu"

x = torch.tensor(encode("qiick")).unsqueeze(0)
T = torch.tensor([5])
print(model.viterbi(x,T)) # should have lower probability---in English only "u" follows "q"

```

    ([[13, 36, 29, 11, 57]], tensor([[-12.3761]], device='cuda:0', grad_fn=<GatherBackward>))
    ([[13, 36, 19, 11, 57]], tensor([[-12.9984]], device='cuda:0', grad_fn=<GatherBackward>))
    ([[13, 36, 43, 11, 57]], tensor([[-18.9938]], device='cuda:0', grad_fn=<GatherBackward>))
    ([[13, 36, 19, 11, 57]], tensor([[-21.7014]], device='cuda:0', grad_fn=<GatherBackward>))

## Conclusion

HMMs used to be very popular in natural language processing, but they have largely been overshadowed by neural network models like RNNs and Transformers. Still, it is fun and instructive to study the HMM; some commonly used machine learning techniques like [Connectionist Temporal Classification](https://www.cs.toronto.edu/~graves/icml_2006.pdf) are inspired by HMM methods. HMMs are [still used in conjunction with neural networks in speech recognition](https://arxiv.org/abs/1811.07453), where the assumption of a one-hot state makes sense for modelling phonemes, which are spoken one at a time.

## Acknowledgments

This notebook is based partly on Lawrence Rabiner's excellent article "[A Tutorial on Hidden Markov Models and Selected Applications in Speech Recognition](https://www.cs.cmu.edu/~cga/behavior/rabiner1.pdf)", which you may also like to check out. Thanks also to Dima Serdyuk and Kyle Gorman for their feedback on the draft.


# Effective Range Expansion plot

Notebook which plots Effective range exapansion by reading in files

## Imports

```python
from itertools import product

import numpy as np
import pandas as pd

from matplotlib.pylab import plt
import seaborn as sns

from luescher_nd.zeta.zeta3d import DispersionZeta3d
from luescher_nd.zeta.extern.pyzeta import zeta as zeta_cont

from luescher_nd.utilities import get_laplace_coefficients

from sympy import S
```

```python
%load_ext blackcellmagic
```

## Parameters & Files

```python
HBARC = 197.326 # MeV / fm
M_NUCLEON = (938.27 + 939.57) / 2 / HBARC # in fm^{-1}

mu = M_NUCLEON / 2
```

```python
FILEREAD = "../data/luescher-3d-res-mom-nstep-inf.csv"
FILEREAD = "../data/luescher-3d-dispersion-final.csv"

df = pd.read_csv(FILEREAD, dtype={"nstep": "Int64"})

df.loc[df.nstep.isna(), "nstep"] = -1

df["L"] = df["n1d_max"] * df["epsilon"]
df["x"] = df["energy"] * mu * df["L"] ** 2 / 2 / np.pi ** 2

df["y"] = np.nan
df["continuum"] = False

for L, epsilon, nstep in product(df.L.unique(), df.epsilon.unique(), df.nstep.unique()):
    ind = (df.L == L) & (df.epsilon == epsilon) & (df.nstep == nstep)

    nstep = nstep if nstep > 0 else None
    zeta = DispersionZeta3d(L, epsilon, nstep=nstep)
    free_x = np.unique(zeta._get_n2())
    df.loc[ind, "continuum"] = df.loc[ind, "x"].apply(
        lambda val: np.abs(val - free_x).min() < 0.05
    )
    df.loc[ind, "y"] = zeta(df.loc[ind, "x"].values) / np.pi / L

df["nstep"] = df.apply(
    lambda row: "$\infty$" if row["nstep"] < 0 else f"${row['nstep']}$", axis=1
)

df = df[df.continuum == False]
df = df.drop_duplicates(["epsilon", "nstep", "y"]).dropna()

df = df.sort_values(["x", "n1d_max", "nstep"], ascending=[True, True, True])

df.head()

```

## Plot

```python
ymax = 0.5

g = sns.FacetGrid(
    df,
    col="nstep",
    hue="n1d_max",
    hue_kws={"marker": ["s", "o", "v", "d"]},
    palette="cubehelix",
    xlim=(-0.1, 19),
    #ylim=(-0.01, ymax),
    col_order=sorted(df.nstep.unique())
)

g.map(plt.plot, "x", "y", ms=1, lw=0.5, ls="--")

g.set_xlabels("$x$")
g.set_ylabels(r"$\frac{S_3^{Lat}(x)}{\pi L}$")

g.add_legend(title=r"$\frac{L}{\epsilon}$", fontsize=6)

x = np.linspace(-1, 20, 1000)

L = 1.0
epsilon= 0.1

zeta = DispersionZeta3d(L, epsilon)
for ax in g.axes[0]:
    ax.axhline(0, c="black", lw=0.2)
    ax.axvline(0, c="black", lw=0.2)
    ax.set_yscale("log")
    #ax.plot(x, zeta(x)/np.pi/L, "--", lw=0.1, ms=0.1)

g.fig.set_dpi(300)
g.fig.set_figheight(2)
g.fig.set_figwidth(6)

plt.show(g.fig)
```
filename = "S3lat-results-nstep-exact-disperion.pdf"
g.fig.savefig(filename, bbox_inches="tight")
!open $filename


# Routhov kriterij stabilnosti

Routhov kriterij stabilnosti bitna je analitička metoda analize stabilnosti sustava, u ovom slučaju Python uvelike pomaže za rješavanje Routhove tablice, no ne može u potpunosti dati izraze za područje stabilnosti sustava u slučajevima gdje imamo više varijabli; iz razloga što ```Sympy``` nije u mogućnosti rješavati nejednadžbe s više varijabli.

Python funkcije koje se koriste za ove operacije dio su ```Sympy``` knjiznice.
```python
* symbols
* Poly
* Matrix
* solve
* plot_implicit
* sympy.matrices.zeros
```

```python
import os
clear = lambda: os.system('cls')
clear()
```

    0

```python
from sympy.interactive import printing
printing.init_printing(use_latex=True)

from sympy import symbols, Poly, Matrix, solve, plot_implicit, reduce_inequalities
from sympy.matrices import zeros
s = symbols('s')
```

## Funkcija za računanje Routhovog kriterija stabilnosti
Iz razloga što ```Control Systems Library``` nema definiranu funkciju za računanje Routhovog kriterija stabilnosti potrebno ju je definirati.
*Algoritam preuzet s CODE LV bloga: http://blog.codelv.com/2013/02/control-systems-in-python-part-2.html*

```python
def routhHurwitz(Ts,*args):
    den = Poly(Ts.as_numer_denom()[1],s).all_coeffs()
    n = len(den)-1
    if n < 2:
        return None
    m = zeros(n+1)
    c = [den[i] for i in range(0,n+1,2)]
    for i in range(0,len(c)):
        m[0,i] = c[i]
    c = [den[i] for i in range(1,n+1,2)]
    for i in range(0,len(c)):
        m[1,i] = c[i]

    for i in range(2,n+1):
        for j in range(1,n):
            if m[i-1,j] == 0:
                m[i,j-1] = m[i-2,j]
            elif m[i-1,0] !=0:
                m[i,j-1] = ((m[i-1,0]*m[i-2,j]-m[i-2,0]*m[i-1,j])/m[i-1,0]).together().simplify()

    m = m.col_insert(0, Matrix(([s**(n-i) for i in range(0,n+1)])))
    return m
```

```python
tf = (s / (s**3+2*s**2+4*s+12))
display(tf)
```

Putem funkcije ```routhHurwitz()``` dobivamo Routhovu tablicu.

```python
routhHurwitz(tf)
```

$$\left[\begin{matrix}s^{3} & 1 & 4 & 0 & 0\\s^{2} & 2 & 12 & 0 & 0\\s & -2 & 0 & 0 & 0\\1 & 12 & 0 & 0 & 0\end{matrix}\right]$$

### Primjer 2: Osnove Regulacijske Tehnike - Stabilnost sustava - Primjer 8

```python
K = symbols('K')
tf = ((10*K*s+30*K) / (s**4+3*s**3+4*s**2+(10*K+4)*s+30*K))
display(tf)
```

```python
matrica = routhHurwitz(tf)
display(matrica)
```

$$\left[\begin{matrix}s^{4} & 1 & 4 & 30 K & 0 & 0\\s^{3} & 3 & 10 K + 4 & 0 & 0 & 0\\s^{2} & - \frac{10 K}{3} + \frac{8}{3} & 30 K & 0 & 0 & 0\\s & \frac{50 K^{2} + 115 K - 16}{5 K - 4} & 0 & 0 & 0 & 0\\1 & 30 K & 0 & 0 & 0 & 0\end{matrix}\right]$$

```python
uvjet1 = matrica[0, 3]
uvjet1 = uvjet1>0
display(uvjet1)
plot_implicit(uvjet1)
solve(uvjet1)
```

```python
uvjet2 = matrica[1,2]
uvjet2 = uvjet2>0
display(uvjet2)
plot_implicit(uvjet2)
solve(uvjet2)
```

```python
uvjet3 = matrica[2, 1]
uvjet3 = uvjet3>0
display(uvjet3)
plot_implicit(uvjet3)
solve(uvjet3)
```

```python
uvjet4 = matrica[2, 2]
uvjet4 = uvjet4>0
display(uvjet4)
plot_implicit(uvjet4)
solve(uvjet4)
```

```python
uvjet5 = matrica[3, 1]
uvjet5 = uvjet5>0
display(uvjet5)
plot_implicit(uvjet5)
solve(uvjet5)
```

```python
uvjet6 = matrica[4, 1]
uvjet6 = uvjet6>0
display(uvjet6)
plot_implicit(uvjet6)
solve(uvjet6)
```

## Primjer 3: Osnove Regulacijske Tehnike - Stabilnost sustava - Primjer 7

```Sympy``` ne može rješavati nejednadžbe s više varijabli, no i dalje smo u mogućnosti dobiti Routhov kriterij stabilnosti te grafički prikazati stabilno područje ```plot_implicit(NEJEDNAKOST)``` funkcijom.

Potrebno je obratiti pažnju na što je u prikazu, u slučajevima s dvije varijable prikaz ne mora značiti područje stabilnosti.

```python
K1, K2 = symbols('K1 K2', real=True, rational=True)
T1, T2 = symbols('T1 T2')
t1 = 0.05
t2 = 0.1
```

```python
tf = (K1*K2) / ((T1*T2*s**3) + (T1+T2)*s**2 + (1+T1*K2)*s + K2 + (K1*K2))
display(tf)
tf = tf.subs(T1, t1)
tf = tf.subs(T2, t2)
display(tf)
```

```python
matrica = routhHurwitz(tf)
display(matrica)
```

$$\left[\begin{matrix}s^{3} & 0.005 & 0.05 K_{2} + 1.0 & 0 & 0\\s^{2} & 0.15 & 1.0 K_{1} K_{2} + 1.0 K_{2} & 0 & 0\\s & - 0.0333333333333333 K_{1} K_{2} + 0.0166666666666667 K_{2} + 1.0 & 0 & 0 & 0\\1 & 1.0 K_{1} K_{2} + 1.0 K_{2} & 0 & 0 & 0\end{matrix}\right]$$

U slučajevima gdje prikazujemo graf u zavisnosti dvije varijable, recimo u ovom slučaju ```K1``` i ```K2```; možemo definirati koja os u grafu se odnosi na koju varijablu putem argumenta
```... , y_var=K1, x_var=K2)``` u funkciji ```plot_implicit(NEJEDNAKOST, ARGUMENT)```

```python
uvjet1 = matrica[0,2]
uvjet1 = uvjet1>0
display(uvjet1)
plot_implicit(uvjet1, y_var=K1, x_var=K2)
solve(uvjet1)
```

```python
uvjet2 = matrica[1, 2]
uvjet2 = uvjet2>0
display(uvjet2)
plot_implicit(uvjet2, y_var=K1, x_var=K2)
```

```python
uvjet3 = matrica[2, 1]
uvjet3 = uvjet3>0
display(uvjet3)
plot_implicit(uvjet3, y_var=K1, x_var=K2)
```

```python
uvjet4 = matrica[3, 1]
uvjet4 = uvjet4>0
display(uvjet4)
plot_implicit(uvjet4, y_var=K1, x_var=K2)
```


# Vellend's (Moran) Drift Model
## python edition

### Getting started
First we have to import a bunch of libraries to do the things we want to do. I will be using:
- numpy: let's us do vectorized math and has lots of useful functions (I do not endore the numpy "core team" they are assholes)
- matplotlib: let's us make plots (not as good as ggplot, seem like good people)
- seaborn: more plotting options (also not as good as ggplot)
- tqdm: progress bar, these models get slooooow

```python
import numpy as np
import matplotlib.pyplot as plt
import ipywidgets as widgets
from tqdm.notebook import tqdm
%matplotlib inline
%matplotlib widget
```

## The Moran Model
The Moran model is a population genetic model first proposed by Patrick Moran in 1958. (I know a Pat Moran but he's just a terrible DJ.) In its most basic form, The Moran model tracks the changes in allele frequency due purely to genetic drift.

We imagine a haploid population that has one of two alleles for some gene, say `A` and `a`. We randomly replace individuals in the population with these two alleles until one completely takes over and the other goes extinct.

It seems to me, after reading this chapter that Vellend's whole idea is based around not just the application of the ideas of population genetic 'fundamental forces' but also population genetic _models_. The Moran model is classic and well understood analytically. This means that if we buy into the idea of the population genetic forces we get some nice results for free. The big shift is that instead of talking about alleles, we talk about species and instead of talking about a population, we talk about a community.

In vellends description, we choose a number of years ($Y$) and for each year we perform the same set of operations a number of times equal to the number of individuals in our community ($N$). These operations are depicted here:

The steps above are labelled with numbers:
1. Chose a random individual to die (maybe shouldn't have used pictured of my best friend!)
2. Chose a random living individual to reproduce
3. Replace the dead individual with a member of the reproducing individual

We perform each of these steps $Y \times N$ times. We can precisely define some of the relevant quantities. We're going to define $S_i$ as the species label of individual $i$. Then we can define the species frequency and some important probabilities.

First, the frequency each species ($s$). This is just a fancy way of saying the number of members of one species divided by the total community size.
\begin{align}
f_s = \frac{\sum_{i=0}^N \delta_{S_i s}}{N}
\end{align}

What is important is the two species case that we consider in this chapter.
\begin{align}
f_1 = \frac{\sum_{i=0}^N \delta_{S_i 1}}{N}; \; \; f_2 = 1 - f_1
\end{align}

In the steps above we draw randomly from the community which means that the probability of an individual of species 1 being chosen for reproduction is really simple.
\begin{align}
P_{birth}(S = 1) = f_1; \;\; P_{birth}(S=2) = 1 - f_1
\end{align}

This is dumb and obvious but later, when we introduce selection it will be much less straight-forward.

## Implementation of the Moran Model
My implementation is very similar to Vellend's though I've changed some names of variables and obviously its in python rather than R. If you are interested in the R code shown in the book it is _not_ available at the link in the text but can be found [here](http://mvellend.recherche.usherbrooke.ca/TOEC.html).

Here is a list of the variables as listed in Vellend as well as the name I've used, and the symbol I've used in the math if appropriate.

| Vellend's R       | Pat's python      | Math symbol       |
| :---------------- | :---------------  | -----------------:|
| `J`               | `n_indiv`         | $N$ |
| `init.1`          | `init_f1`         | $f_1$ |
| `COM`             | `comm`            |             |
| `num.years`       | `n_years`         | $Y$ |
| `freq.1`          | `f1`              | $f_1$ |

He also does some stuff in single lines that I've expanded into multiple lines (hopefully) for clarity.

Finally I defined mine as a function which will allow us to use some little interactive controls.

```python
def moran_model(n_indiv, n_years, init_f1):
    """ Implements the Moran model and simulates it in time.

        Parameters
        ----------
        n_indiv: int
            number of individuals in the community
        n_years: int
            number of potential 'turnovers' of the community
        init_f1: float
            initial frequency of species 1

        Return
        ------
        moran: np.array (n_years, 2)
            contains the species frequencies for each year of the simulation """

    # set up an empty array for the simulated frequencies
    # initialize with the given frequency. python counts from 0, sorrryyyy
    moran = np.zeros((n_years, 2))
    moran[0] = np.array([init_f1, 1 - init_f1])

    # get a vector representing the community. vellend calls this COM
    # this just makes a random vector drawn from the initial frequency
    comm = np.random.choice([0, 1], size=n_indiv, replace=True, p=moran[0])

    # now we can do the loop as in vellend. I'm going to write it a bit differently
    # but the idea is basically the same. (yes its slower)
    for year in range(1, n_years):

        # for each year we potentially replace each individual so we can loop
        # over that as well
        for indiv in range(n_indiv):
            # get probability of species 1
            f1 = np.sum(comm == 0) / n_indiv

            # replace one individual with another
            death = np.random.randint(n_indiv)
            birth = np.random.choice([0, 1], p=[f1, 1 - f1])
            comm[death] = birth

        # when we're done looping over all of the individuals we can update
        # frequencies for the year (the timescale we care about)
        f1 = np.sum(comm == 0) / n_indiv
        moran[year] = np.array([f1, 1 - f1])

    return moran
```

### Running the simulations and visualization
This is all very messy looking. Such is plotting in python. I think I'm not really going to explain the point other than to say that the first part draws some hopefully attractive plots and the second part let's us do that interactively with a simple graphical interface.

```python
def draw_simulation(iterations=10, individuals=250, years=50, initial_freq=0.5):
    # the plot bit, this just makes a blank plot
    fig, ax = plt.subplots(ncols=2, figsize=(10,4), sharey=True, gridspec_kw = {'width_ratios':[3, 1]})
    # trajectory labels
    ax[0].set_xlabel('Years')
    ax[0].set_ylabel('Species 1 frequency')
    ax[0].set_ylim([0, 1.01])
    # distribution labels and bins
    hist_bins = np.arange(0, 1.1, 0.1)
    ax[1].set_xlabel('Count')
    ax[1].set_xlim([0, iterations])

    # we're going to plot a distribution too need an array for it
    dist = np.zeros(iterations)

    # we run the simulation and draw a trajectory
    for i in tqdm(range(iterations)):
        simulation = moran_model(individuals, years, initial_freq)
        ax[0].plot(range(years), simulation[:, 0], c='C0')
        # add final freq to our dist array
        dist[i] = simulation[-1, 0]

    # plot the distribution too
    ax[1].hist(dist, bins=hist_bins, orientation='horizontal')
    ax[1].axhline(np.mean(dist), linestyle='--')

    plt.tight_layout()
    plt.show()

# set up the interface
widgets.interact_manual(draw_simulation, iterations=(5, 50, 5), individuals=(10, 100, 10), years=(5, 200, 5),
                  initial_freq=(0.0, 1.0, 0.01))
```

    interactive(children=(IntSlider(value=10, description='iterations', max=50, min=5, step=5), IntSlider(value=10…

    <function __main__.draw_simulation(iterations=10, individuals=250, years=50, initial_freq=0.5)>

```python

```