```python
%matplotlib inline
```

使用 PyTorch 进行 深度学习
**************************
翻译者： http://www.studyai.com/antares

深度学习构建块: 仿射映射, 非线性单元 和 目标函数
==========================================================================

深度学习包括以聪明的方式组合线性和非线性。非线性的引入使模型变得很强大。
在本节中，我们将使用这些核心组件，构造一个目标函数，并查看模型是如何训练的。

仿射映射
~~~~~~~~~~~

深度学习的核心工作之一是仿射映射(affine map)，它是一个函数 $f(x)$ ，其中

\begin{align}f(x) = Ax + b\end{align}

对矩阵 $A$ 和向量 $x, b$. 这里我们要学习的参数就是 $A$ 和 $b$.
通常, $b$ 被称之为 偏置项(the *bias* term)。

PyTorch和大多数其他深度学习框架所做的事情与传统的线性代数略有不同。它映射输入的行而不是列。
也就是说，下面第 $i$ 行的输出是输入的第 $i$ 行的映射，再加上偏置项。看下面的例子。

```python
# Author: Robert Guthrie

import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim

torch.manual_seed(1)
```

```python
lin = nn.Linear(5, 3)  # maps from R^5 to R^3, parameters A, b
# data is 2x5.  A maps from 5 to 3... can we map "data" under A?
data = torch.randn(2, 5)
print(lin(data))  # yes
```

非线性单元
~~~~~~~~~~~~~~~

首先, 注意以下事实, 它告诉我们为什么需要非线性单元。假定 我们有两个仿射映射：
$f(x) = Ax + b$ 和 $g(x) = Cx + d$ 。 那么 $f(g(x))$ 是什么呢？

\begin{align}f(g(x)) = A(Cx + d) + b = ACx + (Ad + b)\end{align}

$AC$ 是一个矩阵 而 $Ad + b$ 是一个向量, 因此我们看到组合仿射映射之后的结果还是仿射映射。

从这里，你可以看到，如果你想要你的神经网络是很多仿射变换构成的长链条，这并没有为你的模型增加新的能力，
你的模型，最终只是做单个仿射映射而已。

如果我们在仿射层之间引入非线性，情况就不再是这样了，我们可以建立更强大的模型。

已经有一些核心的非线性单元: $\tanh(x), \sigma(x), \text{ReLU}(x)$ 是最常见的。
你或许会质疑: "为什么非得是这些非线性函数? 我可以想到的其他形式的非线性函数多如牛毛"。
这主要是因为它们的梯度非常容易计算，而且梯度计算在学习中有着至关重要的作用。
比如说：

\begin{align}\frac{d\sigma}{dx} = \sigma(x)(1 - \sigma(x))\end{align}

注意：虽然你在AI类的介绍中学到了一些神经网络，其中 $\sigma(x)$ 是默认的非线性单元，
但在实践中人们通常回避它。这是因为梯度随着参数绝对值的增长而迅速消失。
小梯度意味着很难学习。大多数人默认为tanh或relu。

```python
# 在 pytorch 中, 大多数非线性单元是在 torch.nn.functional (我们将它导入为F)
# 注意，非线性单元通常没有仿射映射那样的可学习参数。也就是说，他们没有在训练中更新的权重。
data = torch.randn(2, 2)
print(data)
print(F.relu(data))
```

软最大化 和 概率分布
~~~~~~~~~~~~~~~~~~~~~~~~~

函数 $\text{Softmax}(x)$ 也是一个非线性函数，但它的特殊之处在于它通常是网络中的最后一次运算。
这是因为它接受一个实数向量，并返回一个概率分布。
其定义如下。设 $x$ 是实数向量(正的，负的，随便什么，没有约束)。
那么 $\text{Softmax}(x)$ 的第 i 个分量是:

\begin{align}\frac{\exp(x_i)}{\sum_j \exp(x_j)}\end{align}

应该清楚的是，输出是一个概率分布：每个元素都是非负的，所有分量之和等于 1。

你也可以认为它只是对输入向量进行按元素的指数运算，使一切非负，然后除以归一化常数。

```python
# Softmax 也在 torch.nn.functional 中
data = torch.randn(5)
print(data)
print(F.softmax(data, dim=0))
print(F.softmax(data, dim=0).sum())  # Sums to 1 because it is a distribution!
print(F.log_softmax(data, dim=0))  # theres also log_softmax
```

目标函数
~~~~~~~~~~~~~~~~~~~

目标函数是您的网络正在被训练以最小化的函数(在这种情况下，它通常被称为损失函数
*loss function* 或代价(成本)函数 *cost function*)。
首先选择一个训练实例，通过你的神经网络运行它，然后计算输出的损失。
然后利用损失函数的导数对模型的参数进行更新。直觉地说，如果你的模型对它的答案完全有信心，
而且它的答案是错误的，那么你的损失就会很大。如果它对它的答案很有信心，
而且它的答案是正确的，那么损失就会很小。

在你的训练样例上最小化损失函数的思想是，希望您的网络能够很好地泛化(generalize)，
并在开发集、测试集或生产中的未见过的样例中损失较小。
一个典型的损失函数是负对数似然损失(*negative log likelihood loss*)，
这是多类分类的一个非常常见的目标。对于有监督的多类分类，
这意味着训练网络最小化正确输出的负对数概率(或等效地，最大化正确输出的对数概率)。

优化和训练
=========================

那么，我们能为一个实例计算一个损失函数吗？那我们该怎么办？我们早些时候看到张量知道如何计算该张量
相对于那些计算出它的变量的梯度。既然我们的损失是张量，我们就可以计算所有用于计算它的参数的梯度！
然后我们可以执行标准梯度更新。设 $\theta$ 为我们的参数，$L(\theta)$  为损失函数，
$\eta$ 为正的学习速率.然后:

\begin{align}\theta^{(t+1)} = \theta^{(t)} - \eta \nabla_\theta L(\theta)\end{align}

有大量的算法和积极的研究试图做的不仅仅是这个普通的梯度更新。许多人试图根据训练时段发生的情况来改变学习速度。
除非您真正感兴趣，否则您不需要担心这些算法具体做了什么。Torch在 Torch.optim 包中提供了许多学习速率调节策略，而且它们都是完全透明的。
使用最简单的梯度更新和更复杂的算法是一样的。尝试不同的更新算法和更新算法的不同参数
(比如不同的初始学习速率)对于优化网络的性能非常重要。
通常，用Adam或RMSProp这样的优化器代替普通的SGD会显着地提高性能。

在 PyTorch 中创建神经网络组件
======================================

在我们继续关注NLP之前，让我们做一个带注释的例子，在PyTorch中使用仿射映射和非线性来构建网络。
我们还将看到如何计算损失函数，使用PyTorch的负对数似然，并通过反向传播更新参数。

所有网络组件都应该继承nn.Module并覆盖forward()方法。嗯，没错，就是这样一个套路。
从nn.Module继承可以为组件提供很多功能。例如，它可以跟踪它的可训练参数，
您可以使用 ``.to(device)`` 方法在CPU和GPU之间交换它，
其中设备可以是CPU设备 ``torch.device("cpu")`` 或CUDA设备 ``torch.device("cuda:0")`` 。

让我们编写一个带标注的示例网络，它接受稀疏的词袋表示(sparse bag-of-words representation)，
并在两个标签上输出概率分布：“英语”和“西班牙语”。这个模型只是个Logistic回归模型。

案例: Logistic回归词袋分类器
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

我们的模型将把稀疏词袋(BoW)表示映射到标签上的概率。我们为词汇库(vocab)的单词分配一个索引(index)。
例如，假设我们的整个词汇是两个单词“hello”和“world”，索引分别为0和1。
"hello hello hello hello" 这个句子的BoW向量是

\begin{align}\left[ 4, 0 \right]\end{align}

对于句子 "hello world world hello" 的 BoW 向量是

\begin{align}\left[ 2, 2 \right]\end{align}

etc. 通用意义上说, 它是

\begin{align}\left[ \text{Count}(\text{hello}), \text{Count}(\text{world}) \right]\end{align}

把这个BoW向量记为 $x$ 。 那么我们网络的输出是:

\begin{align}\log \text{Softmax}(Ax + b)\end{align}

那就是说, 我们传递输入使其通过一个仿射映射，然后做对数软最大化(log softmax).

```python
data = [("me gusta comer en la cafeteria".split(), "SPANISH"),
        ("Give it to me".split(), "ENGLISH"),
        ("No creo que sea una buena idea".split(), "SPANISH"),
        ("No it is not a good idea to get lost at sea".split(), "ENGLISH")]

test_data = [("Yo creo que si".split(), "SPANISH"),
             ("it is lost on me".split(), "ENGLISH")]

# word_to_ix maps each word in the vocab to a unique integer, which will be its
# index into the Bag of words vector
word_to_ix = {}
for sent, _ in data + test_data:
    for word in sent:
        if word not in word_to_ix:
            word_to_ix[word] = len(word_to_ix)
print(word_to_ix)

VOCAB_SIZE = len(word_to_ix)
NUM_LABELS = 2

class BoWClassifier(nn.Module):  # inheriting from nn.Module!

    def __init__(self, num_labels, vocab_size):
        # calls the init function of nn.Module.  Dont get confused by syntax,
        # just always do it in an nn.Module
        super(BoWClassifier, self).__init__()

        # Define the parameters that you will need.  In this case, we need A and b,
        # the parameters of the affine mapping.
        # Torch defines nn.Linear(), which provides the affine map.
        # Make sure you understand why the input dimension is vocab_size
        # and the output is num_labels!
        self.linear = nn.Linear(vocab_size, num_labels)

        # NOTE! The non-linearity log softmax does not have parameters! So we don't need
        # to worry about that here

    def forward(self, bow_vec):
        # Pass the input through the linear layer,
        # then pass that through log_softmax.
        # Many non-linearities and other functions are in torch.nn.functional
        return F.log_softmax(self.linear(bow_vec), dim=1)

def make_bow_vector(sentence, word_to_ix):
    vec = torch.zeros(len(word_to_ix))
    for word in sentence:
        vec[word_to_ix[word]] += 1
    return vec.view(1, -1)

def make_target(label, label_to_ix):
    return torch.LongTensor([label_to_ix[label]])

model = BoWClassifier(NUM_LABELS, VOCAB_SIZE)

# 模型知道它的参数.  下面的第一个输出是A, 第二个输出是 b。
# 不论何时，你给一个module的 __init__() 函数中的类变量分配一个组件
# 就像这一句做的这样：self.linear = nn.Linear(...)
# 然后通过一些 Python的魔法函数，你的module(本例中的 BoWClassifier )将会存储关于 nn.Linear 的参数的知识
for param in model.parameters():
    print(param)

# 要运行这个模型, 传递一个 BoW vector
# 这里我们先不考虑训练, 因此代码被封装在 torch.no_grad() 中：
with torch.no_grad():
    sample = data[0]
    bow_vector = make_bow_vector(sample[0], word_to_ix)
    log_probs = model(bow_vector)
    print(log_probs)
```

以上哪个值对应于英语的对数概率(log probability)，哪个值对应于西班牙语？我们从来没有定义过它，
但是如果我们想训练它的话，我们就需要这样做。

```python
label_to_ix = {"SPANISH": 0, "ENGLISH": 1}
```

所以让我们训练吧！为此，我们把样本实例传给网络获取输出的对数概率，计算损失函数的梯度，然后用梯度更新一步参数。
损失函数由PyTorch中的nn包提供。nn.nLLoss() 是我们想要的负对数似然损失(negative log likelihood loss)。
PyTorch中的torch.optim包中定义了优化函数。在这里，我们将只使用SGD。

注意，NLLoss的 *input*  是对数概率的向量还有目标标签向量。它不计算我们的对数概率(log probabilities)。
这就是为什么我们网络的最后一层是 log softmax。损失函数nn.CrossEntroyLoss()与NLLoss()相同，
只是它为您做了log softmax。

```python
# 在我们训练之前在测试数据上运行一下模型, 这么做是想把训练前后模型在测试数据上的输出做个对比
with torch.no_grad():
    for instance, label in test_data:
        bow_vec = make_bow_vector(instance, word_to_ix)
        log_probs = model(bow_vec)
        print(log_probs)

# Print the matrix column corresponding to "creo"
print(next(model.parameters())[:, word_to_ix["creo"]])

loss_function = nn.NLLLoss()
optimizer = optim.SGD(model.parameters(), lr=0.1)

# 通常，您要传递好几次训练数据。100次epoch比在实际数据集上的epoch大得多，
# 但实际数据集有两个以上的实例。通常，在5至30个epoch之间是合理的。
for epoch in range(100):
    for instance, label in data:
        # Step 1. 请记住，PyTorch累积了梯度。我们需要在每个样例(或batch)之前清除它们
        model.zero_grad()

        # Step 2. 产生我们的BOW向量，同时，我们必须将目标装在一个整数张量中。
        # 例如，如果目标是西班牙语，那么我们包装整数0。然后，
        # 损失函数知道对数概率向量的第0元素是与西班牙语对应的对数概率。
        bow_vec = make_bow_vector(instance, word_to_ix)
        target = make_target(label, label_to_ix)

        # Step 3. 运行我们的前向传递过程.
        log_probs = model(bow_vec)

        # Step 4. 计算 loss, gradients, 并通过调用 optimizer.step() 更新参数
        loss = loss_function(log_probs, target)
        loss.backward()
        optimizer.step()

with torch.no_grad():
    for instance, label in test_data:
        bow_vec = make_bow_vector(instance, word_to_ix)
        log_probs = model(bow_vec)
        print(log_probs)

# Index corresponding to Spanish goes up, English goes down!
print(next(model.parameters())[:, word_to_ix["creo"]])
```

我们得到了正确的答案！您可以看到，在第一个样例中西班牙语的对数概率要高得多，
而在第二个测试数据中英语的对数概率要高得多，这是应该的。

现在，您将看到如何制作PyTorch组件，通过它传递一些数据并进行梯度更新。
我们准备深入挖掘深度NLP所能提供的内容。


# Computational Physics  Lectures: Linear Algebra methods

 **Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

Date: **Sep 4, 2017**

Copyright 1999-2017, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license

## Important Matrix and vector handling packages

The Numerical Recipes codes have been rewritten in Fortran 90/95 and
C/C++ by us.  The original source codes are taken from the widely used
software package LAPACK, which follows two other popular packages
developed in the 1970s, namely EISPACK and LINPACK.

  * LINPACK: package for linear equations and least square problems.

  * LAPACK:package for solving symmetric, unsymmetric and generalized eigenvalue problems. From LAPACK's website <http://www.netlib.org> it is possible to download for free all source codes from this library. Both C/C++ and Fortran versions are available.

  * BLAS (I, II and III): (Basic Linear Algebra Subprograms) are routines that provide standard building blocks for performing basic vector and matrix operations. Blas I is vector operations, II vector-matrix operations and III matrix-matrix operations. Highly parallelized and efficient codes, all available for download from <http://www.netlib.org>.

## Basic Matrix Features

**Matrix properties reminder.**

$$
\mathbf{A} =
      \begin{bmatrix} a_{11} & a_{12} & a_{13} & a_{14} \\
                                 a_{21} & a_{22} & a_{23} & a_{24} \\
                                   a_{31} & a_{32} & a_{33} & a_{34} \\
                                  a_{41} & a_{42} & a_{43} & a_{44}
             \end{bmatrix}\qquad
\mathbf{I} =
      \begin{bmatrix} 1 & 0 & 0 & 0 \\
                                 0 & 1 & 0 & 0 \\
                                 0 & 0 & 1 & 0 \\
                                 0 & 0 & 0 & 1
             \end{bmatrix}
$$

## Basic Matrix Features
The inverse of a matrix is defined by

$$
\mathbf{A}^{-1} \cdot \mathbf{A} = I
$$

## Basic Matrix Features

**Matrix Properties Reminder.**

              Relations               	       Name     	                             matrix elements

   $A = A^{T}$                               	    symmetric          	    $a_{ij} = a_{ji}$

   $A = \left (A^{T} \right )^{-1}$          	    real orthogonal    	    $\sum_k a_{ik} a_{jk} = \sum_k a_{ki} a_{kj} = \delta_{ij}$

   $A = A^{ * }$                             	    real matrix        	    $a_{ij} = a_{ij}^{ * }$

   $A = A^{\dagger}$                         	    hermitian          	    $a_{ij} = a_{ji}^{ * }$

   $A = \left (A^{\dagger} \right )^{-1}$    	    unitary            	    $\sum_k a_{ik} a_{jk}^{ * } = \sum_k a_{ki}^{ * } a_{kj} = \delta_{ij}$

## Some famous Matrices

  * Diagonal if $a_{ij}=0$ for $i\ne j$

  * Upper triangular if $a_{ij}=0$ for $i > j$

  * Lower triangular if $a_{ij}=0$ for $i < j$

  * Upper Hessenberg if $a_{ij}=0$ for $i > j+1$

  * Lower Hessenberg if $a_{ij}=0$ for $i < j+1$

  * Tridiagonal if $a_{ij}=0$ for $|i -j| > 1$

  * Lower banded with bandwidth $p$: $a_{ij}=0$ for $i > j+p$

  * Upper banded with bandwidth $p$: $a_{ij}=0$ for $i < j+p$

  * Banded, block upper triangular, block lower triangular....

## Basic Matrix Features

**Some Equivalent Statements.**

For an $N\times N$ matrix  $\mathbf{A}$ the following properties are all equivalent

  * If the inverse of $\mathbf{A}$ exists, $\mathbf{A}$ is nonsingular.

  * The equation $\mathbf{Ax}=0$ implies $\mathbf{x}=0$.

  * The rows of $\mathbf{A}$ form a basis of $R^N$.

  * The columns of $\mathbf{A}$ form a basis of $R^N$.

  * $\mathbf{A}$ is a product of elementary matrices.

  * $0$ is not eigenvalue of $\mathbf{A}$.

## Important Mathematical Operations

The basic matrix operations that we will deal with are addition and subtraction

$$
\begin{equation}
\mathbf{A}= \mathbf{B}\pm\mathbf{C}  \Longrightarrow a_{ij} = b_{ij}\pm c_{ij},
\label{eq:mtxadd} \tag{1}
\end{equation}
$$

scalar-matrix multiplication

$$
\begin{equation}
\mathbf{A}= \gamma\mathbf{B}  \Longrightarrow a_{ij} = \gamma b_{ij},
\label{_auto1} \tag{2}
\end{equation}
$$

vector-matrix multiplication

## Important Mathematical Operations

$$
\begin{equation}
\mathbf{y}=\mathbf{Ax}   \Longrightarrow y_{i} = \sum_{j=1}^{n} a_{ij}x_j,
\label{eq:vecmtx} \tag{3}
\end{equation}
$$

matrix-matrix multiplication

$$
\begin{equation}
\mathbf{A}=\mathbf{BC}   \Longrightarrow a_{ij} = \sum_{k=1}^{n} b_{ik}c_{kj},
\label{eq:mtxmtx} \tag{4}
\end{equation}
$$

and transposition

$$
\begin{equation}
\mathbf{A}=\mathbf{B}^T   \Longrightarrow a_{ij} = b_{ji}
\label{_auto2} \tag{5}
\end{equation}
$$

## Important Mathematical Operations

Similarly, important vector operations that we will deal with are addition and subtraction

$$
\begin{equation}
\mathbf{x}= \mathbf{y}\pm\mathbf{z}  \Longrightarrow x_{i} = y_{i}\pm z_{i},
\label{_auto3} \tag{6}
\end{equation}
$$

scalar-vector multiplication

$$
\begin{equation}
\mathbf{x}= \gamma\mathbf{y}  \Longrightarrow x_{i} = \gamma y_{i},
\label{_auto4} \tag{7}
\end{equation}
$$

vector-vector multiplication (called Hadamard multiplication)
## Important Mathematical Operations

$$
\begin{equation}
\mathbf{x}=\mathbf{yz}   \Longrightarrow x_{i} = y_{i}z_i,
\label{_auto5} \tag{8}
\end{equation}
$$

the inner or so-called dot product  resulting in a constant

$$
\begin{equation}
x=\mathbf{y}^T\mathbf{z}   \Longrightarrow x = \sum_{j=1}^{n} y_{j}z_{j},
\label{eq:innerprod} \tag{9}
\end{equation}
$$

and the outer product, which yields a matrix,

$$
\begin{equation}
\mathbf{A}=  \mathbf{yz}^T \Longrightarrow  a_{ij} = y_{i}z_{j},
\label{eq:outerprod} \tag{10}
\end{equation}
$$

## Matrix Handling in C/C++, Static and Dynamical allocation

**Static.**

We have  an $N\times N$ matrix A  with $N=100$
In C/C++ this would be  defined as

           int N = 100;
           double A[100][100];
           //   initialize all elements to zero
           for(i=0 ; i < N ; i++) {
              for(j=0 ; j < N ; j++) {
                 A[i][j] = 0.0;

Note the way the matrix is organized, row-major order.

## Matrix Handling in C/C++

**Row Major Order, Addition.**

We have  $N\times N$ matrices A, B and C and we wish to
evaluate $A=B+C$.

$$
\mathbf{A}= \mathbf{B}\pm\mathbf{C}  \Longrightarrow a_{ij} = b_{ij}\pm c_{ij},
$$

In C/C++ this would be coded like

           for(i=0 ; i < N ; i++) {
              for(j=0 ; j < N ; j++) {
                 a[i][j] = b[i][j]+c[i][j]

## Matrix Handling in C/C++

**Row Major Order, Multiplication.**

We have  $N\times N$ matrices A, B and C and we wish to
evaluate $A=BC$.

$$
\mathbf{A}=\mathbf{BC}   \Longrightarrow a_{ij} = \sum_{k=1}^{n} b_{ik}c_{kj},
$$

In C/C++ this would be coded like

           for(i=0 ; i < N ; i++) {
              for(j=0 ; j < N ; j++) {
                 for(k=0 ; k < N ; k++) {
                    a[i][j]+=b[i][k]*c[k][j];

## Matrix Handling in Fortran 90/95

**Column Major Order.**

           ALLOCATE (a(N,N), b(N,N), c(N,N))
           DO j=1,  N
              DO i=1, N
                 a(i,j)=b(i,j)+c(i,j)
              ENDDO
           ENDDO
           ...
           DEALLOCATE(a,b,c)

Fortran 90 writes the above statements in a much simpler way

           a=b+c

Multiplication

           a=MATMUL(b,c)

Fortran contains also the intrinsic functions TRANSPOSE and CONJUGATE.

## Dynamic memory allocation in C/C++

At least three possibilities in this course

  * Do it yourself

  * Use the functions provided in the library package lib.cpp

  * Use Armadillo <http://arma.sourceforgenet> (a C++ linear algebra library, discussion both here and at lab).

## Matrix Handling in C/C++, Dynamic Allocation

**Do it yourself.**

        int N;
        double **  A;
        A = new double*[N]
        for ( i = 0; i < N; i++)
            A[i] = new double[N];

Always free space when you don't need an array anymore.

        for ( i = 0; i < N; i++)
            delete[] A[i];
        delete[] A;

## Armadillo, recommended!!

  * Armadillo is a C++ linear algebra library (matrix maths) aiming towards a good balance between speed and ease of use. The syntax is deliberately similar to Matlab.

  * Integer, floating point and complex numbers are supported, as well as a subset of trigonometric and statistics functions. Various matrix decompositions are provided through optional integration with LAPACK, or one of its high performance drop-in replacements (such as the multi-threaded MKL or ACML libraries).

  * A delayed evaluation approach is employed (at compile-time) to combine several operations into one and reduce (or eliminate) the need for temporaries. This is accomplished through recursive templates and template meta-programming.

  * Useful for conversion of research code into production environments, or if C++ has been decided as the language of choice, due to speed and/or integration capabilities.

  * The library is open-source software, and is distributed under a license that is useful in both open-source and commercial/proprietary contexts.

## Armadillo, simple examples

        #include <iostream>
        #include <armadillo>

        using namespace std;
        using namespace arma;

        int main(int argc, char** argv)
          {
          mat A = randu<mat>(5,5);
          mat B = randu<mat>(5,5);

          cout << A*B << endl;

          return 0;

## Armadillo, how to compile and install

For people using Ubuntu, Debian, Linux Mint, simply go to the synaptic package manager and install
armadillo from there.
You may have to install Lapack as well.
For Mac and Windows users, follow the instructions from the webpage
<http://arma.sourceforge.net>.
To compile, use for example (linux/ubuntu)

        c++ -O2 -o program.x program.cpp  -larmadillo -llapack -lblas

where the `-l` option indicates the library you wish to link to.

For OS X users you may have to declare the paths to the include files and the libraries as

        c++ -O2 -o program.x program.cpp  -L/usr/local/lib -I/usr/local/include -larmadillo -llapack -lblas

## Armadillo, simple examples

        #include <iostream>
        #include "armadillo"
        using namespace arma;
        using namespace std;

        int main(int argc, char** argv)
          {
          // directly specify the matrix size (elements are uninitialised)
          mat A(2,3);
          // .n_rows = number of rows    (read only)
          // .n_cols = number of columns (read only)
          cout << "A.n_rows = " << A.n_rows << endl;
          cout << "A.n_cols = " << A.n_cols << endl;
          // directly access an element (indexing starts at 0)
          A(1,2) = 456.0;
          A.print("A:");
          // scalars are treated as a 1x1 matrix,
          // hence the code below will set A to have a size of 1x1
          A = 5.0;
          A.print("A:");
          // if you want a matrix with all elements set to a particular value
          // the .fill() member function can be used
          A.set_size(3,3);
          A.fill(5.0);  A.print("A:");

## Armadillo, simple examples

          mat B;

          // endr indicates "end of row"
          B << 0.555950 << 0.274690 << 0.540605 << 0.798938 << endr
            << 0.108929 << 0.830123 << 0.891726 << 0.895283 << endr
            << 0.948014 << 0.973234 << 0.216504 << 0.883152 << endr
            << 0.023787 << 0.675382 << 0.231751 << 0.450332 << endr;

          // print to the cout stream
          // with an optional string before the contents of the matrix
          B.print("B:");

          // the << operator can also be used to print the matrix
          // to an arbitrary stream (cout in this case)
          cout << "B:" << endl << B << endl;
          // save to disk
          B.save("B.txt", raw_ascii);
          // load from disk
          mat C;
          C.load("B.txt");
          C += 2.0 * B;
          C.print("C:");

## Armadillo, simple examples

          // submatrix types:
          //
          // .submat(first_row, first_column, last_row, last_column)
          // .row(row_number)
          // .col(column_number)
          // .cols(first_column, last_column)
          // .rows(first_row, last_row)

          cout << "C.submat(0,0,3,1) =" << endl;
          cout << C.submat(0,0,3,1) << endl;

          // generate the identity matrix
          mat D = eye<mat>(4,4);

          D.submat(0,0,3,1) = C.cols(1,2);
          D.print("D:");

          // transpose
          cout << "trans(B) =" << endl;
          cout << trans(B) << endl;

          // maximum from each column (traverse along rows)
          cout << "max(B) =" << endl;
          cout << max(B) << endl;

## Armadillo, simple examples

          // maximum from each row (traverse along columns)
          cout << "max(B,1) =" << endl;
          cout << max(B,1) << endl;
          // maximum value in B
          cout << "max(max(B)) = " << max(max(B)) << endl;
          // sum of each column (traverse along rows)
          cout << "sum(B) =" << endl;
          cout << sum(B) << endl;
          // sum of each row (traverse along columns)
          cout << "sum(B,1) =" << endl;
          cout << sum(B,1) << endl;
          // sum of all elements
          cout << "sum(sum(B)) = " << sum(sum(B)) << endl;
          cout << "accu(B)     = " << accu(B) << endl;
          // trace = sum along diagonal
          cout << "trace(B)    = " << trace(B) << endl;
          // random matrix -- values are uniformly distributed in the [0,1] interval
          mat E = randu<mat>(4,4);
          E.print("E:");

## Armadillo, simple examples

          // row vectors are treated like a matrix with one row
          rowvec r;
          r << 0.59499 << 0.88807 << 0.88532 << 0.19968;
          r.print("r:");

          // column vectors are treated like a matrix with one column
          colvec q;
          q << 0.81114 << 0.06256 << 0.95989 << 0.73628;
          q.print("q:");

          // dot or inner product
          cout << "as_scalar(r*q) = " << as_scalar(r*q) << endl;

            // outer product
          cout << "q*r =" << endl;
          cout << q*r << endl;

          // sum of three matrices (no temporary matrices are created)
          mat F = B + C + D;
          F.print("F:");

            return 0;

## Armadillo, simple examples

        #include <iostream>
        #include "armadillo"
        using namespace arma;
        using namespace std;

        int main(int argc, char** argv)
          {
          cout << "Armadillo version: " << arma_version::as_string() << endl;

          mat A;

          A << 0.165300 << 0.454037 << 0.995795 << 0.124098 << 0.047084 << endr
            << 0.688782 << 0.036549 << 0.552848 << 0.937664 << 0.866401 << endr
            << 0.348740 << 0.479388 << 0.506228 << 0.145673 << 0.491547 << endr
            << 0.148678 << 0.682258 << 0.571154 << 0.874724 << 0.444632 << endr
            << 0.245726 << 0.595218 << 0.409327 << 0.367827 << 0.385736 << endr;

          A.print("A =");

          // determinant
          cout << "det(A) = " << det(A) << endl;

## Armadillo, simple examples

          // inverse
          cout << "inv(A) = " << endl << inv(A) << endl;
          double k = 1.23;

          mat    B = randu<mat>(5,5);
          mat    C = randu<mat>(5,5);

          rowvec r = randu<rowvec>(5);
          colvec q = randu<colvec>(5);

          // examples of some expressions
          // for which optimised implementations exist
          // optimised implementation of a trinary expression
          // that results in a scalar
          cout << "as_scalar( r*inv(diagmat(B))*q ) = ";
          cout << as_scalar( r*inv(diagmat(B))*q ) << endl;

          // example of an expression which is optimised
          // as a call to the dgemm() function in BLAS:
          cout << "k*trans(B)*C = " << endl << k*trans(B)*C;

            return 0;

## Gaussian Elimination

We start with the linear set of equations

$$
\mathbf{A}\mathbf{x} = \mathbf{w}.
$$

We assume also that the matrix $\mathbf{A}$ is non-singular and that the
matrix elements along the diagonal satisfy $a_{ii} \ne 0$. Simple $4\times 4 $ example

$$
\begin{bmatrix}
                           a_{11}& a_{12} &a_{13}& a_{14}\\
                           a_{21}& a_{22} &a_{23}& a_{24}\\
                           a_{31}& a_{32} &a_{33}& a_{34}\\
                           a_{41}& a_{42} &a_{43}& a_{44}\\
                      \end{bmatrix} \begin{bmatrix}
                           x_1\\
                           x_2\\
                           x_3 \\
                           x_4  \\
                      \end{bmatrix}
  =\begin{bmatrix}
                           w_1\\
                           w_2\\
                           w_3 \\
                           w_4\\
                      \end{bmatrix}.
$$

## Gaussian Elimination
or

$$
a_{11}x_1 +a_{12}x_2 +a_{13}x_3 + a_{14}x_4=w_1 \nonumber
$$

$$
a_{21}x_1 + a_{22}x_2 + a_{23}x_3 + a_{24}x_4=w_2 \nonumber
$$

$$
a_{31}x_1 + a_{32}x_2 + a_{33}x_3 + a_{34}x_4=w_3 \nonumber
$$

$$
a_{41}x_1 + a_{42}x_2 + a_{43}x_3 + a_{44}x_4=w_4. \nonumber
$$

## Gaussian Elimination

The basic idea of Gaussian elimination is to use the first equation to eliminate the first unknown $x_1$
from the remaining $n-1$ equations. Then we use the new second equation to eliminate the second unknown
$x_2$ from the remaining $n-2$ equations. With $n-1$ such eliminations
we obtain a so-called upper triangular set of equations of the form

$$
b_{11}x_1 +b_{12}x_2 +b_{13}x_3 + b_{14}x_4=y_1 \nonumber
$$

$$
b_{22}x_2 + b_{23}x_3 + b_{24}x_4=y_2 \nonumber
$$

$$
b_{33}x_3 + b_{34}x_4=y_3 \nonumber
$$

$$
b_{44}x_4=y_4. \nonumber
\label{eq:gaussbacksub} \tag{11}
$$

We can solve this system of equations recursively starting from $x_n$ (in our case $x_4$) and proceed with
what is called a backward substitution.

## Gaussian Elimination
This process can be expressed mathematically as

$$
\begin{equation}
   x_m = \frac{1}{b_{mm}}\left(y_m-\sum_{k=m+1}^nb_{mk}x_k\right)\quad m=n-1,n-2,\dots,1.
\label{_auto6} \tag{12}
\end{equation}
$$

To arrive at such an upper triangular system of equations, we start by eliminating
the unknown $x_1$ for $j=2,n$. We achieve this by multiplying the first equation by $a_{j1}/a_{11}$ and then subtract
the result from the $j$th equation. We assume obviously that $a_{11}\ne 0$ and that
$\mathbf{A}$ is not singular.

## Gaussian Elimination

Our actual $4\times 4$ example reads after the first operation

$$
\begin{bmatrix}
                           a_{11}& a_{12} &a_{13}& a_{14}\\
                           0& (a_{22}-\frac{a_{21}a_{12}}{a_{11}}) &(a_{23}-\frac{a_{21}a_{13}}{a_{11}}) & (a_{24}-\frac{a_{21}a_{14}}{a_{11}})\\
0& (a_{32}-\frac{a_{31}a_{12}}{a_{11}})& (a_{33}-\frac{a_{31}a_{13}}{a_{11}})& (a_{34}-\frac{a_{31}a_{14}}{a_{11}})\\
0&(a_{42}-\frac{a_{41}a_{12}}{a_{11}}) &(a_{43}-\frac{a_{41}a_{13}}{a_{11}}) & (a_{44}-\frac{a_{41}a_{14}}{a_{11}}) \\
                      \end{bmatrix} \begin{bmatrix}
                           x_1\\
                           x_2\\
                           x_3 \\
                           x_4  \\
                      \end{bmatrix}
  =\begin{bmatrix}
                           y_1\\
                           w_2^{(2)}\\
                           w_3^{(2)} \\
                           w_4^{(2)}\\
                      \end{bmatrix},
$$

or

$$
b_{11}x_1 +b_{12}x_2 +b_{13}x_3 + b_{14}x_4=y_1 \nonumber
$$

$$
a^{(2)}_{22}x_2 + a^{(2)}_{23}x_3 + a^{(2)}_{24}x_4=w^{(2)}_2 \nonumber
$$

$$
a^{(2)}_{32}x_2 + a^{(2)}_{33}x_3 + a^{(2)}_{34}x_4=w^{(2)}_3 \nonumber
$$

$$
a^{(2)}_{42}x_2 + a^{(2)}_{43}x_3 + a^{(2)}_{44}x_4=w^{(2)}_4, \nonumber
$$

$$
\begin{equation}
\label{_auto7} \tag{13}
\end{equation}
$$

## Gaussian Elimination

The new coefficients are

$$
\begin{equation}
   b_{1k} = a_{1k}^{(1)} \quad k=1,\dots,n,
\label{_auto8} \tag{14}
\end{equation}
$$

where each $a_{1k}^{(1)}$ is equal to the original $a_{1k}$ element. The other coefficients are

$$
\begin{equation}
a_{jk}^{(2)} = a_{jk}^{(1)}-\frac{a_{j1}^{(1)}a_{1k}^{(1)}}{a_{11}^{(1)}} \quad j,k=2,\dots,n,
\label{_auto9} \tag{15}
\end{equation}
$$

with a new right-hand side given by

$$
\begin{equation}
y_{1}=w_1^{(1)}, \quad w_j^{(2)} =w_j^{(1)}-\frac{a_{j1}^{(1)}w_1^{(1)}}{a_{11}^{(1)}} \quad j=2,\dots,n.
\label{_auto10} \tag{16}
\end{equation}
$$

We have also set $w_1^{(1)}=w_1$, the original vector element.
We see that the system of unknowns $x_1,\dots,x_n$ is transformed into an $(n-1)\times (n-1)$ problem.

## Gaussian Elimination

This step is called forward substitution.
Proceeding with these substitutions, we obtain the
general expressions for the new coefficients

$$
\begin{equation}
   a_{jk}^{(m+1)} = a_{jk}^{(m)}-\frac{a_{jm}^{(m)}a_{mk}^{(m)}}{a_{mm}^{(m)}} \quad j,k=m+1,\dots,n,
\label{_auto11} \tag{17}
\end{equation}
$$

with $m=1,\dots,n-1$ and a
right-hand side given by

$$
\begin{equation}
   w_j^{(m+1)} =w_j^{(m)}-\frac{a_{jm}^{(m)}w_m^{(m)}}{a_{mm}^{(m)}}\quad j=m+1,\dots,n.
\label{_auto12} \tag{18}
\end{equation}
$$

This set of $n-1$ elimations leads us to an equations which is solved by back substitution.
If the arithmetics is exact and the matrix $\mathbf{A}$ is not singular, then the computed answer will be exact.

Even though the matrix elements along the diagonal are not zero,
numerically small numbers may appear and subsequent divisions may lead to large numbers, which, if added
to a small number may yield losses of precision. Suppose for example that our first division in $(a_{22}-a_{21}a_{12}/a_{11})$
results in $-10^{-7}$ and that $a_{22}$ is one.
one. We are then
adding $10^7+1$. With single precision this results in $10^7$.

## Gaussian Elimination and Tridiagonal matrices, project 1

Suppose we want to solve the following boundary value equation

$$
-\frac{d^2u(x)}{dx^2} = f(x,u(x)),
$$

with $x\in (a,b)$ and with boundary conditions $u(a)=u(b) = 0$.
We assume that $f$ is a continuous function in the domain $x\in (a,b)$.
Since, except the few cases where it is possible to find analytic solutions, we
will seek after approximate solutions, we choose to represent the approximation to the second derivative
from the previous chapter

$$
f''=\frac{f_h -2f_0 +f_{-h}}{h^2} +O(h^2).
$$

We subdivide our interval $x\in (a,b)$ into $n$ subintervals by setting $x_i = ih$, with $i=0,1,\dots,n+1$.
The step size is then given by $h=(b-a)/(n+1)$ with $n\in {\mathbb{N}}$.
For the internal grid points $i=1,2,\dots n$ we replace the differential operator with the above formula
resulting in

$$
u''(x_i) \approx  \frac{u(x_i+h) -2u(x_i) +u(x_i-h)}{h^2},
$$

which we rewrite as

$$
u^{''}_i \approx  \frac{u_{i+1} -2u_i +u_{i-i}}{h^2}.
$$

## Gaussian Elimination and Tridiagonal matrices, project 1

We can rewrite our original differential equation in terms of a discretized equation with approximations to the
derivatives as

$$
-\frac{u_{i+1} -2u_i +u_{i-i}}{h^2}=f(x_i,u(x_i)),
$$

with $i=1,2,\dots, n$. We need to add to this system the two boundary conditions $u(a) =u_0$ and $u(b) = u_{n+1}$.
If we define a matrix

$$
\mathbf{A} = \frac{1}{h^2}\begin{bmatrix}
                          2 & -1 &  &   &  & \\
                          -1 & 2 & -1 & & & \\
                           & -1 & 2 & -1 & &  \\
                           & \dots   & \dots &\dots   &\dots & \dots \\
                           &   &  &-1  &2& -1 \\
                           &    &  &   &-1 & 2 \\
                      \end{bmatrix}
$$

and the corresponding vectors $\mathbf{u} = (u_1, u_2, \dots,u_n)^T$ and
$\mathbf{f}(\mathbf{u}) = f(x_1,x_2,\dots, x_n,u_1, u_2, \dots,u_n)^T$  we can rewrite the differential equation
including the boundary conditions as a system of linear equations with  a large number of unknowns

$$
\mathbf{A}\mathbf{u} = \mathbf{f}(\mathbf{u}).
$$

## Gaussian Elimination and Tridiagonal matrices, project 1

We start with the linear set of equations

$$
\mathbf{A}\mathbf{u} = \mathbf{f},
$$

where $\mathbf{A}$ is a tridiagonal matrix which we rewrite as

$$
\mathbf{A} = \begin{bmatrix}
                           b_1& c_1 & 0 &\dots   & \dots &\dots \\
                           a_2 & b_2 & c_2 &\dots &\dots &\dots \\
                           & a_3 & b_3 & c_3 & \dots & \dots \\
                           & \dots   & \dots &\dots   &\dots & \dots \\
                           &   &  &a_{n-1}  &b_{n-1}& c_{n-1} \\
                           &    &  &   &a_n & b_n \\
                      \end{bmatrix}
$$

where $a,b,c$ are one-dimensional arrays of length $1:n$.
In project 1 the arrays $a$ and $c$ are equal, namely $a_i=c_i=-1/h^2$.
The matrix is  also positive definite.

## Gaussian Elimination and Tridiagonal matrices, project 1

We can rewrite as

$$
\mathbf{A} = \begin{bmatrix}
                           b_1& c_1 & 0 &\dots   & \dots &\dots \\
                           a_2 & b_2 & c_2 &\dots &\dots &\dots \\
                           & a_3 & b_3 & c_3 & \dots & \dots \\
                           & \dots   & \dots &\dots   &\dots & \dots \\
                           &   &  &a_{n-1}  &b_{n-1}& c_{n-1} \\
                           &    &  &   &a_n & b_n \\
                      \end{bmatrix} \begin{bmatrix}
                           u_1\\
                           u_2\\
                           \dots \\
                          \dots  \\
                          \dots \\
                           u_n\\
                      \end{bmatrix}
  =\begin{bmatrix}
                           f_1\\
                           f_2\\
                           \dots \\
                           \dots \\
                          \dots \\
                           f_n\\
                      \end{bmatrix}.
$$

## Gaussian Elimination and Tridiagonal matrices, project 1

A tridiagonal matrix is a special form of banded matrix where all the elements are zero except for
those on and immediately above and below the leading diagonal.
The above tridiagonal system   can be written as

$$
a_iu_{i-1}+b_iu_i+c_iu_{i+1} = f_i,
$$

for $i=1,2,\dots,n$. We see that $u_{-1}$ and $u_{n+1}$ are not required and we can set $a_1=c_n=0$.
In many applications the matrix is symmetric and we have $a_i=c_i$.
The algorithm for solving this set of equations is rather simple and requires two steps only,
a forward substitution and a backward substitution. These steps are also
common to the algorithms based on
Gaussian elimination that
we discussed previously. However, due to its simplicity, the number of floating point operations
is in this
case proportional with $O(n)$ while Gaussian elimination requires $2n^3/3+O(n^2)$ floating point operations.

## Gaussian Elimination and Tridiagonal matrices, project 1

In case your system of equations leads to a tridiagonal matrix, it is clearly an overkill to employ
Gaussian elimination or the standard LU decomposition.

Our algorithm starts with forward substitution with a loop over of the elements $i$ and gives an update of the diagonal elements $b_i$
given by the new diagonals $\tilde{b}_i$

$$
\tilde{b}_i= b_i - \frac{a_ic_{i-1}}{\tilde{b}_{i-1}},
$$

and the new righthand side $\tilde{f}_i$ given by

$$
\tilde{f}_i= f_i - \frac{a_i\tilde{f}_{i-1}}{\tilde{b}_{i-1}}.
$$

Recall that $\tilde{b}_1=b_1$ and $\tilde{f}_1=f_1$ always.

## Backward substitution

The backward substitution gives then the final solution

$$
u_{i-1}= \frac{\tilde{f}_{i-1}-c_{i-1}u_i}{\tilde{b}_{i-1}},
$$

with $u_n=\tilde{f}_{n}/\tilde{b}_{n}$ when $i=n$, the last point.

## Gaussian Elimination and Tridiagonal matrices, project 1

The matrix $\mathbf{A}$ which rephrases a second derivative in a discretized form is much simpler than the general matrix

$$
\mathbf{A} = \begin{bmatrix}
                          2 & -1 & 0 & 0  &0  & 0\\
                          -1 & 2 & -1 &0 &0 &0 \\
                          0 & -1 & 2 & -1 & 0& 0 \\
                          0 & \dots   & \dots & \dots   &\dots & \dots \\
                          0 &0   &0  &-1  &2& -1 \\
                          0 &  0  &0  &0   &-1 & 2 \\
                      \end{bmatrix}.
$$

This matrix fulfills the condition of a weak dominance of the diagonal, with
$|b_1| > |c_1|$, $|b_n| > |a_n|$ and  $|b_k| \ge |a_k|+|c_k|$ for $k=2,3,\dots,n-1$.
This is a relevant but not sufficient condition to guarantee that the matrix $\mathbf{A}$ yields a solution to a linear
equation problem. The matrix needs also to be irreducible. A tridiagonal irreducible matrix means that all the elements $a_i$ and
$c_i$ are non-zero. If these two conditions are present, then $\mathbf{A}$ is nonsingular and has a unique LU decomposition.

## Project 1, hints

When setting up the algo it is useful to note that the different
operations on the matrix (here as a $4\times 4$ case  with diagonals
$d_i$ and off-diagonals $e_i$) give is an extremely simple algorithm, namely

$$
\begin{bmatrix}
                          d_1 & e_1 & 0 & 0 \\
                          e_2 & d_2 & e_2 & 0 \\
                          0 & e_3 & d_3 & e_3 \\
                          0 & 0 & e_4 & d_4
                      \end{bmatrix}\rightarrow
                 \begin{bmatrix}
                          d_1 & e_1 & 0 & 0 \\
                          0 & \tilde{d}_2 & e_2 & 0 \\
                          0 & e_3 & d_3 & e_3 \\
                          0 & 0 & e_4 & d_4
                      \end{bmatrix}\rightarrow
                \begin{bmatrix}
                          d_1 & e_1 & 0 & 0 \\
                          0 & \tilde{d}_2 & e_2 & 0 \\
                          0 & 0 & \tilde{d}_3 & e_3 \\
                          0 & 0 & e_4 & d_4
                      \end{bmatrix}
$$

and finally

$$
\begin{bmatrix}
                          d_1 & e_1 & 0 & 0 \\
                          0 & \tilde{d}_2 & e_2 & 0 \\
                          0 & 0 & \tilde{d}_3 & e_3 \\
                          0 & 0 & 0 & \tilde{d}_4
                      \end{bmatrix}
$$

## Project 1, hints

We notice the sub-blocks which get repeated

$$
\begin{bmatrix}
                          d_1 & e_1 & 0 & 0 \\
                          0 & \tilde{d}_2 & e_2 & 0 \\
                          0 & 0 & \tilde{d}_3 & e_3 \\
                          0 & 0 & 0 & \tilde{d}_4
                      \end{bmatrix}
$$

The matrices we often end up with in rewriting for for example partial differential equations,
have the feature that all leading principal submatrices are non-singular.

## Simple expressions for project 1
For the special matrix we can can actually precalculate the updated matrix elements $\tilde{d}_i$. The non-diagonal elements $e_i$ are unchanged.
For our particular matrix in project 1 we have

$$
\tilde{d}_i= 2 - \frac{1}{\tilde{d}_{i-1}}=\frac{i+1}{i},
$$

and the new righthand side $\tilde{f}_i$ given by

$$
\tilde{f}_i= f_i + \frac{(i-1)\tilde{f}_{i-1}}{i}.
$$

Recall that $\tilde{d}_1=2$ and $\tilde{f}_1=f_1$.  These arrays can be set up before computing $u$.

The backward substitution gives then the final solution

$$
u_{i-1}= \frac{i-1}{i}\left(\tilde{f}_{i-1}+u_i\right),
$$

with $u_n=\tilde{f}_{n}/\tilde{b}_{n}$.

## [Program example](https://github.com/CompPhysics/ComputationalPhysicsMSU/blob/master/doc/Projects/2016/Project1/Examples/TridiagonalSimple.cpp)

        #include <iostream>
        #include <fstream>
        #include <iomanip>
        #include <cmath>
        #include <string>
        // use namespace for output and input
        using namespace std;

        // object for output files
        ofstream ofile;
        // Functions used
        inline double f(double x){return 100.0*exp(-10.0*x);
        }
        inline double exact(double x) {return 1.0-(1-exp(-10))*x-exp(-10*x);}

        // Begin main program
        int main(int argc, char *argv[]){
          int exponent;
            string filename;
            // We read also the basic name for the output file and the highest power of 10^n we want
            if( argc <= 1 ){
                  cout << "Bad Usage: " << argv[0] <<
                      " read also file name on same line and max power 10^n" << endl;
                  exit(1);
            }
                else{
                filename = argv[1]; // first command line argument after name of program
                exponent = atoi(argv[2]);
            }
            // Loop over powers of 10
            for (int i = 1; i <= exponent; i++){
              int  n = (int) pow(10.0,i);
              // Declare new file name
              string fileout = filename;
              // Convert the power 10^i to a string
              string argument = to_string(i);
              // Final filename as filename-i-
              fileout.append(argument);
              double h = 1.0/(n);
              double hh = h*h;
              // Set up arrays for the simple case
              double *d = new double [n+1]; double *b = new double [n+1]; double *solution = new double [n+1];
              double *x = new double[n+1];
              // Quick setup of updated diagonal elements and value of
              d[0] = d[n] = 2; solution[0] = solution[n] = 0.0;
              for (int i = 1; i < n; i++) d[i] = (i+1.0)/( (double) i);
              for (int i = 0; i <= n; i++){
        	x[i]= i*h;
                b[i] = hh*f(i*h);
              }
              // Forward substitution
              for (int i = 2; i < n; i++) b[i] = b[i] + b[i-1]/d[i-1];
              // Backward substitution
              solution[n-1] = b[n-1]/d[n-1];
              for (int i = n-2; i > 0; i--) solution[i] = (b[i]+solution[i+1])/d[i];
              ofile.open(fileout);
              ofile << setiosflags(ios::showpoint | ios::uppercase);
              //      ofile << "       x:             approx:          exact:       relative error" << endl;
              for (int i = 1; i < n;i++) {
        	double xval = x[i];
         	 double RelativeError = fabs((exact(xval)-solution[i])/exact(xval));
                 ofile << setw(15) << setprecision(8) << xval;
                 ofile << setw(15) << setprecision(8) << solution[i];
                 ofile << setw(15) << setprecision(8) << exact(xval);
                 ofile << setw(15) << setprecision(8) << log10(RelativeError) << endl;
              }
              ofile.close();
              delete [] x; delete [] d; delete [] b; delete [] solution;
            }
            return 0;
        }

## Linear Algebra Methods

  * Gaussian elimination, $O(2/3n^3)$ flops, general matrix

  * LU decomposition, upper triangular and lower tridiagonal matrices, $O(2/3n^3)$ flops, general matrix. Get easily the inverse, determinant and can solve linear equations with back-substitution only, $O(n^2)$ flops

  * Cholesky decomposition. Real symmetric or hermitian positive definite matrix, $O(1/3n^3)$ flops.

  * Tridiagonal linear systems, important for differential equations. Normally positive definite and non-singular. $O(8n)$ flops for symmetric. Special case of banded matrices.

  * Singular value decomposition

  * the QR method will be discussed in chapter 7 in connection with eigenvalue systems. $O(4/3n^3)$ flops.

## LU Decomposition

The LU decomposition method means that we can rewrite
this matrix as the product of two matrices $\mathbf{L}$ and $\mathbf{U}$
where

$$
\begin{bmatrix}
                          a_{11} & a_{12} & a_{13} & a_{14} \\
                          a_{21} & a_{22} & a_{23} & a_{24} \\
                          a_{31} & a_{32} & a_{33} & a_{34} \\
                          a_{41} & a_{42} & a_{43} & a_{44}
                      \end{bmatrix}
                      = \begin{bmatrix}
                              1  & 0      & 0      & 0 \\
                          l_{21} & 1      & 0      & 0 \\
                          l_{31} & l_{32} & 1      & 0 \\
                          l_{41} & l_{42} & l_{43} & 1
                      \end{bmatrix}
                        \begin{bmatrix}
                          u_{11} & u_{12} & u_{13} & u_{14} \\
                               0 & u_{22} & u_{23} & u_{24} \\
                               0 & 0      & u_{33} & u_{34} \\
                               0 & 0      &  0     & u_{44}
             \end{bmatrix}.
$$

## LU Decomposition

LU decomposition forms the backbone of other algorithms in linear algebra, such as the
solution of linear equations given by

$$
a_{11}x_1 +a_{12}x_2 +a_{13}x_3 + a_{14}x_4=w_1 \nonumber
$$

$$
a_{21}x_1 + a_{22}x_2 + a_{23}x_3 + a_{24}x_4=w_2 \nonumber
$$

$$
a_{31}x_1 + a_{32}x_2 + a_{33}x_3 + a_{34}x_4=w_3 \nonumber
$$

$$
a_{41}x_1 + a_{42}x_2 + a_{43}x_3 + a_{44}x_4=w_4.  \nonumber
$$

The above set of equations is conveniently solved by using LU decomposition as an intermediate step.

The matrix $\mathbf{A}\in \mathbb{R}^{n\times n}$ has an LU factorization if the determinant
is different from zero. If the LU factorization exists and $\mathbf{A}$ is non-singular, then the LU factorization
is unique and the determinant is given by

$$
det\{\mathbf{A}\}=det\{\mathbf{LU}\}= det\{\mathbf{L}\}det\{\mathbf{U}\}=u_{11}u_{22}\dots u_{nn}.
$$

## LU Decomposition, why?

There are at least three main advantages with LU decomposition compared with standard Gaussian elimination:

  * It is straightforward to compute the determinant of a matrix

  * If we have to solve sets of linear equations with the same matrix but with different vectors $\mathbf{y}$, the number of FLOPS is of the order $n^3$.

  * The inverse is such an operation

## LU Decomposition, linear equations

With the LU decomposition it is rather
simple to solve a system of linear equations

$$
a_{11}x_1 +a_{12}x_2 +a_{13}x_3 + a_{14}x_4=w_1 \nonumber
$$

$$
a_{21}x_1 + a_{22}x_2 + a_{23}x_3 + a_{24}x_4=w_2 \nonumber
$$

$$
a_{31}x_1 + a_{32}x_2 + a_{33}x_3 + a_{34}x_4=w_3 \nonumber
$$

$$
a_{41}x_1 + a_{42}x_2 + a_{43}x_3 + a_{44}x_4=w_4. \nonumber
$$

This can be written in matrix form as

$$
\mathbf{Ax}=\mathbf{w}.
$$

where $\mathbf{A}$ and $\mathbf{w}$ are known and we have to solve for
$\mathbf{x}$. Using the LU dcomposition we write

$$
\mathbf{A} \mathbf{x} \equiv \mathbf{L} \mathbf{U} \mathbf{x} =\mathbf{w}.
$$

## LU Decomposition, linear equations

The previous equation can be calculated in two steps

$$
\mathbf{L} \mathbf{y} = \mathbf{w};\qquad \mathbf{Ux}=\mathbf{y}.
$$

To show that this is correct we use to the LU decomposition
to rewrite our system of linear equations as

$$
\mathbf{LUx}=\mathbf{w},
$$

and since the determinat of $\mathbf{L}$ is equal to 1 (by construction
since the diagonals of $\mathbf{L}$ equal 1) we can use the inverse of
$\mathbf{L}$ to obtain

$$
\mathbf{Ux}=\mathbf{L^{-1}w}=\mathbf{y},
$$

which yields the intermediate step

$$
\mathbf{L^{-1}w}=\mathbf{y}
$$

and as soon as we have $\mathbf{y}$ we can obtain $\mathbf{x}$
through $\mathbf{Ux}=\mathbf{y}$.

## LU Decomposition, why?

For our four-dimentional example this takes the form

$$
y_1=w_1 \nonumber
$$

$$
l_{21}y_1 + y_2=w_2\nonumber
$$

$$
l_{31}y_1 + l_{32}y_2 + y_3 =w_3\nonumber
$$

$$
l_{41}y_1 + l_{42}y_2 + l_{43}y_3 + y_4=w_4. \nonumber
$$

and

$$
u_{11}x_1 +u_{12}x_2 +u_{13}x_3 + u_{14}x_4=y_1 \nonumber
$$

$$
u_{22}x_2 + u_{23}x_3 + u_{24}x_4=y_2\nonumber
$$

$$
u_{33}x_3 + u_{34}x_4=y_3\nonumber
$$

$$
u_{44}x_4=y_4  \nonumber
$$

This example shows the basis for the algorithm
needed to solve the set of $n$ linear equations.

## LU Decomposition, linear equations

The algorithm goes as follows

  * Set up the matrix $\bf A$ and the vector $\bf w$ with their correct dimensions. This determines the dimensionality of the unknown vector $\bf x$.

  * Then LU decompose the matrix $\bf A$ through a call to the function `ludcmp(double a, int n, int indx, double &d)`. This functions returns the LU decomposed matrix $\bf A$, its determinant and the vector indx which keeps track of the number of interchanges of rows. If the determinant is zero, the solution is malconditioned.

  * Thereafter you call the function  `lubksb(double a, int n, int indx, double w)` which uses the LU decomposed matrix $\bf A$ and the vector $\bf w$ and returns $\bf x$ in the same place as $\bf w$. Upon exit the original content in $\bf w$ is destroyed. If you wish to keep this information, you should make a backup of it in your calling function.

## LU Decomposition, the inverse of a matrix

If the inverse exists then

$$
\mathbf{A}^{-1}\mathbf{A}=\mathbf{I},
$$

the identity matrix. With an LU decomposed matrix we can rewrite the last equation as

$$
\mathbf{LU}\mathbf{A}^{-1}=\mathbf{I}.
$$

## LU Decomposition, the inverse of a matrix

If we assume that the first column (that is column 1) of the inverse matrix
can be written as a vector with unknown entries

$$
\mathbf{A}_1^{-1}= \begin{bmatrix}
                              a_{11}^{-1} \\
                              a_{21}^{-1} \\
                              \dots \\
                              a_{n1}^{-1} \\
                    \end{bmatrix},
$$

then we have a linear set of equations

$$
\mathbf{LU}\begin{bmatrix}
                              a_{11}^{-1} \\
                              a_{21}^{-1} \\
                              \dots \\
                              a_{n1}^{-1} \\
                    \end{bmatrix} =\begin{bmatrix}
                               1 \\
                              0 \\
                              \dots \\
                              0 \\
                    \end{bmatrix}.
$$

## LU Decomposition, the inverse

In a similar way we can compute the unknow entries of the second column,

$$
\mathbf{LU}\begin{bmatrix}
                              a_{12}^{-1} \\
                              a_{22}^{-1} \\
                              \dots \\
                              a_{n2}^{-1} \\
                    \end{bmatrix}=\begin{bmatrix}
                                0 \\
                              1 \\
                              \dots \\
                              0 \\
                    \end{bmatrix},
$$

and continue till we have solved all $n$ sets of linear equations.

## [How to use the Library functions](https://github.com/CompPhysics/ComputationalPhysicsMSU/tree/master/doc/Programs/LecturePrograms/programs/cppLibrary)

Standard C/C++: fetch the files `lib.cpp` and `lib.h`. You can make a directory where you store
these files, and eventually its compiled version lib.o. The example here is [program1.cpp from chapter 6](https://github.com/CompPhysics/ComputationalPhysicsMSU/blob/master/doc/Programs/LecturePrograms/programs/LinAlgebra/cpp/program1.cpp) and performs the matrix inversion.

        //  Simple matrix inversion example
        #include <iostream>
        #include <new>
        #include <cstdio>
        #include <cstdlib>
        #include <cmath>
        #include <cstring>
        #include "lib.h"

        using namespace std;

        /* function declarations */

        void inverse(double **, int);

## [How to use the Library functions](https://github.com/CompPhysics/ComputationalPhysicsMSU/tree/master/doc/Programs/LecturePrograms/programs/cppLibrary)

        void inverse(double **a, int n)
        {
          int          i,j, *indx;
          double       d, *col, **y;
          // allocate space in memory
          indx = new int[n];
          col  = new double[n];
          y    = (double **) matrix(n, n, sizeof(double));
          ludcmp(a, n, indx, &d);   // LU decompose  a[][]
          printf("\n\nLU form of matrix of a[][]:\n");
          for(i = 0; i < n; i++) {
            printf("\n");
            for(j = 0; j < n; j++) {
              printf(" a[%2d][%2d] = %12.4E",i, j, a[i][j]);

## [How to use the Library functions](https://github.com/CompPhysics/ComputationalPhysicsMSU/tree/master/doc/Programs/LecturePrograms/programs/cppLibrary)

          // find inverse of a[][] by columns
          for(j = 0; j < n; j++) {
            // initialize right-side of linear equations
            for(i = 0; i < n; i++) col[i] = 0.0;
            col[j] = 1.0;
            lubksb(a, n, indx, col);
            // save result in y[][]
            for(i = 0; i < n; i++) y[i][j] = col[i];
          }   //j-loop over columns
          // return the inverse matrix in a[][]
          for(i = 0; i < n; i++) {
            for(j = 0; j < n; j++) a[i][j] = y[i][j];

          free_matrix((void **) y);     // release local memory
          delete [] col;
          delete []indx;
        }  // End: function inverse()

## [How to use the Library functions](https://github.com/CompPhysics/ComputationalPhysicsMSU/tree/master/doc/Programs/LecturePrograms/programs/FortranLibrary)

For Fortran users:

        PROGRAM matrix
          USE constants
          USE F90library
          IMPLICIT NONE
          !      The definition of the matrix, using dynamic allocation
          REAL(DP), ALLOCATABLE, DIMENSION(:,:) :: a, ainv, unity
          !      the determinant
          REAL(DP) :: d
          !      The size of the matrix
          INTEGER :: n
          ....
          !      Allocate now place in heap for a
          ALLOCATE ( a(n,n), ainv(n,n), unity(n,n) )

## [How to use the Library functions](https://github.com/CompPhysics/ComputationalPhysicsMSU/tree/master/doc/Programs/LecturePrograms/programs/FortranLibrary)

For Fortran users:

          WRITE(6,*) ' The matrix before inversion'
          WRITE(6,'(3F12.6)') a
          ainv=a
          CALL matinv (ainv, n, d)
          ....
          !      get the unity matrix
          unity=MATMUL(ainv,a)
          WRITE(6,*) ' The unity matrix'
          WRITE(6,'(3F12.6)') unity
          !      deallocate all arrays
          DEALLOCATE (a, ainv, unity)
        END PROGRAM matrix

## [Using Armadillo to perform an LU decomposition](https://github.com/CompPhysics/ComputationalPhysicsMSU/blob/master/doc/Programs/CppQtCodesLectures/MatrixTest/main.cpp)

        #include <iostream>
        #include "armadillo"
        using namespace arma;
        using namespace std;

        int main()
          {
           mat A = randu<mat>(5,5);
           vec b = randu<vec>(5);

          A.print("A =");
          b.print("b=");
          // solve Ax = b
          vec x = solve(A,b);
          // print x
          x.print("x=");
          // find LU decomp of A, if needed, P is the permutation matrix
          mat L, U;
          lu(L,U,A);
          // print l
          L.print(" L= ");
          // print U
          U.print(" U= ");
          //Check that A = LU
          (A-L*U).print("Test of LU decomposition");
            return 0;
          }

## Iterative methods, Chapter 6
 * Direct solvers such as Gauss elimination and  LU decomposition discussed in connection with project 1.

 * Iterative solvers such as Basic iterative solvers,  Jacobi,  Gauss-Seidel, Successive over-relaxation. These methods are easy to parallelize, as we will se later. Much used in solutions of partial differential equations.

 * Other iterative methods such as Krylov subspace methods with Generalized minimum residual (GMRES) and Conjugate gradient etc will not be discussed.

## Iterative methods, Jacobi's method
It is a simple method for solving

$$
\mathbf{A}\mathbf{x}=\mathbf{b},
$$

where $\mathbf{A}$ is a matrix and $\mathbf{x}$ and $\mathbf{b}$ are vectors. The vector $\mathbf{x}$ is
the unknown.

It is an iterative scheme where we start with a guess for the unknown, and
after $k+1$ iterations we have

$$
\mathbf{x}^{(k+1)}= \mathbf{D}^{-1}(\mathbf{b}-(\mathbf{L}+\mathbf{U})\mathbf{x}^{(k)}),
$$

with $\mathbf{A}=\mathbf{D}+\mathbf{U}+\mathbf{L}$ and
$\mathbf{D}$ being a diagonal matrix, $\mathbf{U}$ an upper triangular matrix and $\mathbf{L}$ a  lower triangular
matrix.

If the matrix $\mathbf{A}$ is positive definite or diagonally dominant, one can show that this method will always converge to the exact solution.

## Iterative methods, Jacobi's method
We can demonstrate Jacobi's method by this $4\times 4$ matrix problem. We assume a guess
for the vector elements $x_i^{(0)}$, a guess which represents our first iteration. The new
values are obtained by substitution

$$
x_1^{(1)} =(b_1-a_{12}x_2^{(0)} -a_{13}x_3^{(0)} - a_{14}x_4^{(0)})/a_{11} \nonumber
$$

$$
x_2^{(1)} =(b_2-a_{21}x_1^{(0)} - a_{23}x_3^{(0)} - a_{24}x_4^{(0)})/a_{22} \nonumber
$$

$$
x_3^{(1)} =(b_3- a_{31}x_1^{(0)} -a_{32}x_2^{(0)} -a_{34}x_4^{(0)})/a_{33} \nonumber
$$

$$
x_4^{(1)}=(b_4-a_{41}x_1^{(0)} -a_{42}x_2^{(0)} - a_{43}x_3^{(0)})/a_{44},  \nonumber
$$

which after $k+1$ iterations reads

$$
x_1^{(k+1)} =(b_1-a_{12}x_2^{(k)} -a_{13}x_3^{(k)} - a_{14}x_4^{(k)})/a_{11} \nonumber
$$

$$
x_2^{(k+1)} =(b_2-a_{21}x_1^{(k)} - a_{23}x_3^{(k)} - a_{24}x_4^{(k)})/a_{22} \nonumber
$$

$$
x_3^{(k+1)} =(b_3- a_{31}x_1^{(k)} -a_{32}x_2^{(k)} -a_{34}x_4^{(k)})/a_{33} \nonumber
$$

$$
x_4^{(k+1)}=(b_4-a_{41}x_1^{(k)} -a_{42}x_2^{(k)} - a_{43}x_3^{(k)})/a_{44},  \nonumber
$$

## Iterative methods, Jacobi's method
We can generalize the above equations to

$$
x_i^{(k+1)}=(b_i-\sum_{j=1, j\ne i}^{n}a_{ij}x_j^{(k)})/a_{ii}
$$

or in an even more compact form as

$$
\mathbf{x}^{(k+1)}= \mathbf{D}^{-1}(\mathbf{b}-(\mathbf{L}+\mathbf{U})\mathbf{x}^{(k)}),
$$

with $\mathbf{A}=\mathbf{D}+\mathbf{U}+\mathbf{L}$ and
$\mathbf{D}$ being a diagonal matrix, $\mathbf{U}$ an upper triangular matrix and $\mathbf{L}$ a  lower triangular
matrix.

## Iterative methods, Gauss-Seidel's method
Our $4\times 4$ matrix problem

$$
x_1^{(k+1)} =(b_1-a_{12}x_2^{(k)} -a_{13}x_3^{(k)} - a_{14}x_4^{(k)})/a_{11} \nonumber
$$

$$
x_2^{(k+1)} =(b_2-a_{21}x_1^{(k)} - a_{23}x_3^{(k)} - a_{24}x_4^{(k)})/a_{22} \nonumber
$$

$$
x_3^{(k+1)} =(b_3- a_{31}x_1^{(k)} -a_{32}x_2^{(k)} -a_{34}x_4^{(k)})/a_{33} \nonumber
$$

$$
x_4^{(k+1)}=(b_4-a_{41}x_1^{(k)} -a_{42}x_2^{(k)} - a_{43}x_3^{(k)})/a_{44},  \nonumber
$$

can be rewritten as

$$
x_1^{(k+1)} =(b_1-a_{12}x_2^{(k)} -a_{13}x_3^{(k)} - a_{14}x_4^{(k)})/a_{11} \nonumber
$$

$$
x_2^{(k+1)} =(b_2-a_{21}x_1^{(k+1)} - a_{23}x_3^{(k)} - a_{24}x_4^{(k)})/a_{22} \nonumber
$$

$$
x_3^{(k+1)} =(b_3- a_{31}x_1^{(k+1)} -a_{32}x_2^{(k+1)} -a_{34}x_4^{(k)})/a_{33} \nonumber
$$

$$
x_4^{(k+1)}=(b_4-a_{41}x_1^{(k+1)} -a_{42}x_2^{(k+1)} - a_{43}x_3^{(k+1)})/a_{44},  \nonumber
$$

which allows us to utilize the preceding solution (forward substitution). This improves normally the convergence
behavior and leads to the Gauss-Seidel method!

## Iterative methods, Gauss-Seidel's method
We can generalize

$$
x_1^{(k+1)} =(b_1-a_{12}x_2^{(k)} -a_{13}x_3^{(k)} - a_{14}x_4^{(k)})/a_{11} \nonumber
$$

$$
x_2^{(k+1)} =(b_2-a_{21}x_1^{(k+1)} - a_{23}x_3^{(k)} - a_{24}x_4^{(k)})/a_{22} \nonumber
$$

$$
x_3^{(k+1)} =(b_3- a_{31}x_1^{(k+1)} -a_{32}x_2^{(k+1)} -a_{34}x_4^{(k)})/a_{33} \nonumber
$$

$$
x_4^{(k+1)}=(b_4-a_{41}x_1^{(k+1)} -a_{42}x_2^{(k+1)} - a_{43}x_3^{(k+1)})/a_{44},  \nonumber
$$

to the following form

$$
x^{(k+1)}_i = \frac{1}{a_{ii}} \left(b_i - \sum_{j > i}a_{ij}x^{(k)}_j - \sum_{j < i}a_{ij}x^{(k+1)}_j \right),\quad i=1,2,\ldots,n.
$$

The procedure is generally continued until the changes made by an iteration are below some tolerance.

The convergence properties of the Jacobi method and the
Gauss-Seidel method are dependent on the matrix $\mathbf{A}$. These methods converge when
the matrix is symmetric positive-definite, or is strictly or irreducibly diagonally dominant.
Both methods sometimes converge even if these conditions are not satisfied.

## Iterative methods, Successive over-relaxation
Given a square system of n linear equations with unknown $\mathbf x$:

$$
\mathbf{A}\mathbf x = \mathbf b
$$

where

$$
\mathbf{A}=\begin{bmatrix} a_{11} & a_{12} & \cdots & a_{1n} \\ a_{21} & a_{22} & \cdots & a_{2n} \\ \vdots & \vdots & \ddots & \vdots \\a_{n1} & a_{n2} & \cdots & a_{nn} \end{bmatrix}, \qquad \mathbf{x} = \begin{bmatrix} x_{1} \\ x_2 \\ \vdots \\ x_n \end{bmatrix} , \qquad \mathbf{b} = \begin{bmatrix} b_{1} \\ b_2 \\ \vdots \\ b_n \end{bmatrix}.
$$

## Iterative methods, Successive over-relaxation
Then A can be decomposed into a diagonal component D, and strictly lower and upper triangular components L and U:

$$
\mathbf{A} =\mathbf{D} + \mathbf{L} + \mathbf{U},
$$

where

$$
D = \begin{bmatrix} a_{11} & 0 & \cdots & 0 \\ 0 & a_{22} & \cdots & 0 \\ \vdots & \vdots & \ddots & \vdots \\0 & 0 & \cdots & a_{nn} \end{bmatrix}, \quad L = \begin{bmatrix} 0 & 0 & \cdots & 0 \\ a_{21} & 0 & \cdots & 0 \\ \vdots & \vdots & \ddots & \vdots \\a_{n1} & a_{n2} & \cdots & 0 \end{bmatrix}, \quad U = \begin{bmatrix} 0 & a_{12} & \cdots & a_{1n} \\ 0 & 0 & \cdots & a_{2n} \\ \vdots & \vdots & \ddots & \vdots \\0 & 0 & \cdots & 0 \end{bmatrix}.
$$

The system of linear equations may be rewritten as:

$$
(D+\omega L) \mathbf{x} = \omega \mathbf{b} - [\omega U + (\omega-1) D ] \mathbf{x}
$$

for a constant $\omega > 1$.

## Iterative methods, Successive over-relaxation
The method of successive over-relaxation is an iterative technique that solves the left hand side of this expression for $x$, using previous value for $x$ on the right hand side. Analytically, this may be written as:

$$
\mathbf{x}^{(k+1)} = (D+\omega L)^{-1} \big(\omega \mathbf{b} - [\omega U + (\omega-1) D ] \mathbf{x}^{(k)}\big).
$$

However, by taking advantage of the triangular form of $(D+\omega L)$, the elements of $x^{(k+1)}$ can be computed sequentially using forward substitution:

$$
x^{(k+1)}_i = (1-\omega)x^{(k)}_i + \frac{\omega}{a_{ii}} \left(b_i - \sum_{j > i} a_{ij}x^{(k)}_j - \sum_{j < i} a_{ij}x^{(k+1)}_j \right),\quad i=1,2,\ldots,n.
$$

The choice of relaxation factor is not necessarily easy, and depends upon the properties of the coefficient matrix. For symmetric, positive-definite matrices it can be proven that $0 < \omega < 2$ will lead to convergence, but we are generally interested in faster convergence rather than just convergence.

## Cubic Splines, Chapter 6
Cubic spline interpolation is among one of the most used
methods for interpolating between data points where the arguments
are organized as ascending series. In the library program we supply
such a function, based on the so-called cubic spline method to be
described below.

A spline function consists of polynomial pieces defined on
subintervals. The different subintervals are connected via
various continuity relations.

Assume we have at our disposal $n+1$ points $x_0, x_1, \dots x_n$
arranged so that $x_0 < x_1 < x_2 < \dots x_{n-1} < x_n$ (such points are called
knots). A spline function $s$ of degree $k$ with $n+1$ knots is defined
as follows
 * On every subinterval $[x_{i-1},x_i)$ *s* is a polynomial of degree $\le k$.

 * $s$ has $k-1$ continuous derivatives in the whole interval $[x_0,x_n]$.

## Splines
As an example, consider a spline function of degree $k=1$ defined as follows

$$
s(x)=\begin{bmatrix} s_0(x)=a_0x+b_0 & x\in [x_0, x_1) \\
                             s_1(x)=a_1x+b_1 & x\in [x_1, x_2) \\
                             \dots & \dots \\
                             s_{n-1}(x)=a_{n-1}x+b_{n-1} & x\in
                             [x_{n-1}, x_n] \end{bmatrix}.
$$

In this case the polynomial consists of series of straight lines
connected to each other at every endpoint. The number of continuous
derivatives is then $k-1=0$, as expected when we deal with straight lines.
Such a polynomial is quite easy to construct given
$n+1$ points $x_0, x_1, \dots x_n$ and their corresponding
function values.

## Splines
The most commonly used spline function is the one with $k=3$, the so-called
cubic spline function.
Assume that we have in adddition to the $n+1$ knots a series of
functions values $y_0=f(x_0), y_1=f(x_1), \dots y_n=f(x_n)$.
By definition, the polynomials $s_{i-1}$ and $s_i$
are thence supposed to interpolate the same point $i$, that is

$$
s_{i-1}(x_i)= y_i = s_i(x_i),
$$

with $1 \le i \le n-1$. In total we have $n$ polynomials of the
type

$$
s_i(x)=a_{i0}+a_{i1}x+a_{i2}x^2+a_{i2}x^3,
$$

yielding $4n$ coefficients to determine.

## Splines
Every subinterval provides in addition the $2n$ conditions

$$
y_i = s(x_i),
$$

and

$$
s(x_{i+1})= y_{i+1},
$$

to be fulfilled. If we also assume that $s'$ and $s''$ are continuous,
then

$$
s'_{i-1}(x_i)= s'_i(x_i),
$$

yields $n-1$ conditions. Similarly,

$$
s''_{i-1}(x_i)= s''_i(x_i),
$$

results in additional $n-1$ conditions. In total we have $4n$ coefficients
and $4n-2$ equations to determine them, leaving us with $2$ degrees of
freedom to be determined.

## Splines
Using the last equation we define two values for the second derivative, namely

$$
s''_{i}(x_i)= f_i,
$$

and

$$
s''_{i}(x_{i+1})= f_{i+1},
$$

and setting up a straight line between $f_i$ and $f_{i+1}$ we have

$$
s_i''(x) = \frac{f_i}{x_{i+1}-x_i}(x_{i+1}-x)+
               \frac{f_{i+1}}{x_{i+1}-x_i}(x-x_i),
$$

and integrating twice one obtains

$$
s_i(x) = \frac{f_i}{6(x_{i+1}-x_i)}(x_{i+1}-x)^3+
               \frac{f_{i+1}}{6(x_{i+1}-x_i)}(x-x_i)^3
             +c(x-x_i)+d(x_{i+1}-x).
$$

## Splines
Using the conditions $s_i(x_i)=y_i$ and $s_i(x_{i+1})=y_{i+1}$
we can in turn determine the constants $c$ and $d$ resulting in

$$
s_i(x) =\frac{f_i}{6(x_{i+1}-x_i)}(x_{i+1}-x)^3+
               \frac{f_{i+1}}{6(x_{i+1}-x_i)}(x-x_i)^3 \nonumber
$$

$$
\begin{equation}
            +(\frac{y_{i+1}}{x_{i+1}-x_i}-\frac{f_{i+1}(x_{i+1}-x_i)}{6})
              (x-x_i)+
             (\frac{y_{i}}{x_{i+1}-x_i}-\frac{f_{i}(x_{i+1}-x_i)}{6})
             (x_{i+1}-x).
\label{_auto13} \tag{19}
\end{equation}
$$

## Splines
How to determine the values of the second
derivatives $f_{i}$ and $f_{i+1}$? We use the continuity assumption
of the first derivatives

$$
s'_{i-1}(x_i)= s'_i(x_i),
$$

and set $x=x_i$. Defining $h_i=x_{i+1}-x_i$ we obtain finally
the following expression

$$
h_{i-1}f_{i-1}+2(h_{i}+h_{i-1})f_i+h_if_{i+1}=
   \frac{6}{h_i}(y_{i+1}-y_i)-\frac{6}{h_{i-1}}(y_{i}-y_{i-1}),
$$

and introducing the shorthands $u_i=2(h_{i}+h_{i-1})$,
$v_i=\frac{6}{h_i}(y_{i+1}-y_i)-\frac{6}{h_{i-1}}(y_{i}-y_{i-1})$,
we can reformulate the problem as a set of linear equations to be
solved  through e.g., Gaussian elemination

## Splines
Gaussian elimination

$$
\begin{bmatrix} u_1 & h_1 &0 &\dots & & & & \\
                                 h_1 & u_2 & h_2 &0 &\dots & & & \\
                                  0   & h_2 & u_3 & h_3 &0 &\dots & & \\
                               \dots& & \dots &\dots &\dots &\dots &\dots & \\
                                 &\dots & & &0 &h_{n-3} &u_{n-2} &h_{n-2} \\
                                 & && & &0 &h_{n-2} &u_{n-1} \end{bmatrix}
   \begin{bmatrix} f_1 \\
                          f_2 \\
                          f_3\\
                          \dots \\
                          f_{n-2} \\
                          f_{n-1} \end{bmatrix} =
   \begin{bmatrix} v_1 \\
                          v_2 \\
                          v_3\\
                          \dots \\
                          v_{n-2}\\
                          v_{n-1} \end{bmatrix}.
$$

Note that this is a set of tridiagonal equations and can be solved
through only $O(n)$ operations.

## Splines
The functions supplied in the program library are *spline* and *splint*.
In order to use cubic spline interpolation you need first to call

        spline(double x[], double y[], int n, double yp1,  double yp2, double y2[])

This function takes as
input $x[0,..,n - 1]$ and $y[0,..,n - 1]$ containing a tabulation
$y_i = f(x_i)$ with $x_0 < x_1 < .. < x_{n - 1}$
together with the
first derivatives  of $f(x)$ at $x_0$ and $x_{n-1}$, respectively. Then the
function returns $y2[0,..,n-1]$ which contains the second derivatives of
$f(x_i)$ at each point $x_i$. $n$ is the number of points.
This function provides the cubic spline interpolation for all subintervals
and is called only once.

## Splines
Thereafter, if you wish to make  various interpolations, you need to call the function

        splint(double x[], double y[], double y2a[], int n, double x, double *y)

which takes as input
the tabulated values $x[0,..,n - 1]$ and $y[0,..,n - 1]$ and the output
y2a[0,..,n - 1] from *spline*. It returns the value $y$ corresponding
to the point $x$.


# Random Signals

*This jupyter notebook is part of a [collection of notebooks](../index.ipynb) on various topics of Digital Signal Processing. Please direct questions and suggestions to [Sascha.Spors@uni-rostock.de](mailto:Sascha.Spors@uni-rostock.de).*

## White Noise

### Definition

[White noise](https://en.wikipedia.org/wiki/White_noise) is a wide-sense stationary (WSS) random signal with constant power spectral density (PSD)

\begin{equation}
\Phi_{xx}(\mathrm{e}^{\,\mathrm{j}\, \Omega}) = N_0
\end{equation}

where $N_0$ denotes the power per frequency. White noise draws its name from the analogy to white light. It refers typically to an idealized model of a random signal, e.g. emerging from measurement noise. The auto-correlation function (ACF) of white noise can be derived by inverse discrete-time Fourier transformation (DTFT) of the PSD

\begin{equation}
\varphi_{xx}[\kappa] = \mathcal{F}_*^{-1} \{ N_0 \} = N_0 \cdot \delta[\kappa]
\end{equation}

This result implies that white noise has to be a zero-mean random process. It can be concluded from the ACF that two neighboring samples $k$ and $k+1$ are uncorrelated. Hence they show no dependencies in the statistical sense. Although this is often assumed, the probability density function (PDF) of white noise is not necessarily given by the normal distribution. In general, it is required to additionally state the amplitude distribution when denoting a signal as white noise.

### Example - Amplifier Noise

Additive white Gaussian noise (AWGN) is often used as a model for amplifier noise. In order to evaluate if this holds for a typical audio amplifier, the noise captured from a microphone preamplifier at full amplification with open connectors is analyzed statistically. For the remainder, a function is defined to estimate and plot the PDF and ACF of a given random signal.

```python
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as stats
%matplotlib inline

def estimate_plot_pdf_acf(x, nbins=50, acf_range=30):

    # compute and truncate ACF
    acf = 1/len(x) * np.correlate(x, x, mode='full')
    acf = acf[len(x)-acf_range-1:len(x)+acf_range-1]
    kappa = np.arange(-acf_range, acf_range)

    # plot PSD
    plt.figure(figsize = (10, 6))
    plt.subplot(121)
    plt.hist(x, nbins, density=True)
    plt.title('Estimated PDF')
    plt.xlabel(r'$\theta$')
    plt.ylabel(r'$\hat{p}_x(\theta)$')
    plt.grid()

    # plot ACF
    plt.subplot(122)
    plt.stem(kappa, acf, use_line_collection=True)
    plt.title('Estimated ACF')
    plt.ylabel(r'$\hat{\varphi}_{xx}[\kappa]$')
    plt.xlabel(r'$\kappa$')
    plt.axis([-acf_range, acf_range, 1.1*min(acf), 1.1*max(acf)]);
    plt.grid()
```

Now the pre-captured noise is loaded and analyzed

```python
noise = np.load('../data/amplifier_noise.npz')['noise']
estimate_plot_pdf_acf(noise, nbins=100, acf_range=150)
```

Inspecting the PDF reveals that it fits quite well to a [normal distribution](important_distributions.ipynb#Normal-Distribution). The ACF consists of a pronounced peak. from which can be concluded that the samples are approximately uncorrelated. Hence, the amplifier noise can be modeled reasonably well as additive white Gaussian noise. In oder to estimate the parameters of the normal distribution, the captured samples are fitted to a normal distribution

```python
mean, sigma = stats.norm.fit(noise)
print('Mean: {0:1.3e} \nVariance: {1:1.3e}'.format(mean, sigma**2))
```

    Mean: -1.537e-05
    Variance: 1.140e-07

**Excercise**

* What relative level does the amplifier noise have when the maximum amplitude of the amplifier is assumed to be $\pm 1$?

Solution: The average power of a mean-free random signal is given by is variance, here $\sigma_\text{noise}^2$. Due to the very low mean in comparison to the maximum amplitude, the noise can be assumed to be mean-free. Hence, the relative level of the noise is then given as $10*\log_{10}\left( \frac{\sigma_\text{noise}^2}{1} \right)$. Numerical evaluation yields

```python
print('Level of amplifier noise: {:2.2f} dB'.format(10*np.log10(sigma**2/1)))
```

    Level of amplifier noise: -69.43 dB

### Example - Generation of White Noise with Different Amplitude Distributions

Toolboxes for numerical mathematics like `Numpy` or `scipy.stats` provide functions to draw uncorrelated random samples with a given amplitude distribution.

**Uniformly distributed white noise**

For samples drawn from a zero-mean random process with uniform amplitude distribution, the PDF and ACF are estimated as

```python
np.random.seed(3)
estimate_plot_pdf_acf(np.random.uniform(size=10000)-1/2)
```

Lets listen to uniformly distributed white noise

```python
from scipy.io import wavfile
fs = 44100

x = np.random.uniform(size=5*fs)-1/2
wavfile.write('uniform_white_noise.wav', fs, np.int16(x*32768))
```

<audio src="./uniform_white_noise.wav" controls>Your browser does not support the audio element.</audio>[./uniform_white_noise.wav](./uniform_white_noise.wav)

**Laplace distributed white noise**

For samples drawn from a zero-mean random process with with Laplace amplitude distribution, the PDF and ACF are estimated as

```python
estimate_plot_pdf_acf(np.random.laplace(size=10000, loc=0, scale=1/np.sqrt(2)))
```

**Exercise**

* Do both random processes represent white noise?
* Estimate the power spectral density $N_0$ of both examples.
* How does the ACF change if you lower the length `size` of the random signal. Why?

Solution: Both processes represent white noise since the ACF can be approximated reasonably well as Dirac impulse $\delta[\kappa]$. The weight of the Dirac impulse is equal to $N_0$. In case of the uniformly distributed white noise $N_0 \approx \frac{1}{12}$, in case of the Laplace distributed white noise $N_0 \approx 1$. Decreasing the length `size` of the signal increases the statistical uncertainties in the estimate of the ACF.

**Copyright**

This notebook is provided as [Open Educational Resource](https://en.wikipedia.org/wiki/Open_educational_resources). Feel free to use the notebook for your own purposes. The text is licensed under [Creative Commons Attribution 4.0](https://creativecommons.org/licenses/by/4.0/), the code of the IPython examples under the [MIT license](https://opensource.org/licenses/MIT). Please attribute the work as follows: *Sascha Spors, Digital Signal Processing - Lecture notes featuring computational examples*.


Introdução
==========

A Covid-19 é uma doença respiratória causada pelo novo coronavírus (SARS-CoV-2). Esse vírus vem causando bastante preocupação no mundo pela sua acelerada disseminação. No Brasil, até a presente data, o
número de casos confirmados passam de 145 mil e de mortos ultrapassa os 10 mil.

Ao mesmo tempo que essa doença se propaga rapidamente, estou interessado em compreender como a propagação de doenças infecciosas podem acontecer.
Existe algum modelo que pode descrever com alguma simplicidade esse contágio?

Descobri que sim. Existe um modelo matemático relativamente simples,
chamado SIR, que descreve a estrutura dessa disseminação. A afirmação do
modelo é tão interessante que resolvi implementar e avaliar como se
comporta na minha realidade local.

Este post tem como objetivo fornecer uma visão geral do modelo SIR e o
resultado da minha simulação usando um conjunto de dados do Covid-19,
fornecidos pelo [portal do Governo do Estado do Amapá](https://www.portal.ap.gov.br/coronavirus).

O que é o modelo SIR
--------------------

O modelo SIR é um tipo de modelo que descreve a dinâmica de doenças infecciosas. O modelo divide a população em três compartimentos e
espera-se que cada compartimento tenhas as mesmas características. Assim, o modelo SIR é segmentado em:

-   **S**uscetíveis
-   **I**nfectados
-   **R**emovidos

Os **Suscetíveis** representam a população total que ainda não tem
imunidade e está vulnerável a exposição da doença. Os **Infectados**
representam a população atual de infectados. Elas podem espalhar a
doença para as pessoas suscetíveis e podem ser removidas desse grupo no
caso de atingirem recuperação (imunidade) ou morte. Já os **Removidos**
representam a população que já adquiriu imunidade e não estão mais
suscetíveis a doença. Nesse caso incluem-se também os mortos (que não
podem disseminar a doença).

O modelo SIR permite descrever o número de pessoas em cada compartimento
com uma equação diferencial ordinária. O parâmetro $\beta$ é a taxa que
controla o quanto a doença pode ser transmitida através da exposição. É
determinado pela chance de contato e pela probabilidade de transmissão
da doença. O parâmetro $\gamma$ expressa a taxa de recuperação da doença
em um período específico. Uma vez que as pessoas são curadas, elas obtêm
imunidade. Não há chance de eles voltarem suscetíveis novamente.

$$
\begin{array}{rcl}
\dfrac{dS}{dt} &=& -\beta \dfrac{I}{N}S\\[10pt]
\dfrac{dI}{dt} &=&  \beta \dfrac{I}{N}S\\[10pt]
\dfrac{dR}{dt} &=& \gamma I
\end{array}
$$

onde $N$ é a população total. E assim, é importante notar
que: $$S + I + R = N$$

Isso mostra uma limitação do modelo. Não consideramos o efeito da taxa
natural de morte ou nascimento, porque o modelo pressupõe que o período
pendente da doença seja muito menor que o tempo de vida do ser humano.
Isso nos permite saber a importância de conhecer dois parâmetros,
$\beta$ e $\gamma$. Quando podemos estimar os dois valores, há várias
ideias derivadas deles. Se consideramos $D$ a média de dias para se
recuperar da infecção, temos que $$D = \frac{1}{\gamma}$$

Além disso, podemos estimar a natureza da doença em termos do poder da
infecção. $$R_0 = \frac{\beta}{\gamma}$$

É chamado de número básico de reprodução. $R_0$ é o número médio de
pessoas infectadas por outra pessoa. Se for alto, a probabilidade de
pandemia também é maior. O número também é usado para estimar o nível de
imunidade do rebanho (HIL, sigla em inglês), isto é, quando uma porção
crítica da população se torna imune e a doença pode não persistir mais
na população, se tornando [endêmica](https://en.wikipedia.org/wiki/Endemic_(epidemiology)). Se o número básico de reprodução
multiplicado pela porcentagem de pessoas não imunes (suscetíveis) for
igual a 1, isso indica o estado equilibrado. O número de pessoas
infecciosas é constante. Suponha que a proporção de pessoas imunes seja
$p$, o estado estável pode ser formulado da seguinte maneira.

$$R_0(1-p) = 1 \rightarrow 1-p = \frac{1}{R_0} \rightarrow p_c = 1-  \frac{1}{R_0}$$

Portanto, $p_c$ é o HIT para parar a propagação da doença infecciosa.
Podemos parar o surto vacinando a população para aumentar a imunidade do
rebanho. O vídeo fornecido pelo **3Blue1Brown** também é um ótimo
recurso para aprender visualmente o modelo SIR.

[](https://www.youtube.com/watch?v=gxAaO2rsdIs "3Blue1Brown")

Agora que sabemos o básico sobre o modelo e sobre as principais métricas, vamos partir para a implementação do código.

Simulação com dados do Covid-19 no Amapá
----------------------------------------

A fonte de dados que usei neste experimento foram coletados até dia 09 de Maio de 2020, no Portal do
Governo do Amapá. É possível fazer o download **aqui**. Nesse arquivo os dados coletados iniciam no dia 04 de Maio, quando começa a apresentar indivíduos removidos, e está organizado em:

-   *Dia*
-   *Confirmados*
-   *Mortes*
-   *Recuperados*

Nessas simulações se considera a população estimada do Amapá ($N=845.731$), pelo [IBGE em 2019](https://www.ibge.gov.br/cidades-e-estados/ap.html). O que vamos fazer é estimar o $\beta$ e $\gamma$ para ajustar o modelo
SIR aos casos confirmados reais (o número de pessoas infectadas). Para
resolver a equação diferencial ordinária como o modelo SIR, podemos usar
a função `solve_ivp` no módulo `scipy`.

### Importandos as principais bibliotecas

```python
# Library
import numpy as np
import matplotlib.pyplot as plt
import plotly.graph_objects as go
import pandas as pd
from scipy.integrate import solve_ivp
from scipy.optimize import minimize
from datetime import date, timedelta
```

### Importando os dados

```python
# import data frame
dados = pd.read_csv('https://marleson.github.io/src/ap-covid-19-SIR-09-05-20.csv')

# Amostra dos dias
Dias = dados['Dias']
# Amostra de casos Confirmados
Confirmed = dados['Confirmados']
# Amostra de casos Recuperados
Recovered = dados['Recuperados']
# Amostra do num. de mortos
Deaths = dados['Mortos']

# Quant. de infectados
Infected = Confirmed - Recovered - Deaths

# Quant. de Removidos
Removed = Recovered + Deaths

# Populacao do Amapa, N.
N = 845731

# Número inicial de indivíduos infectados e removidos, I_start e R_start.
I_start, R_start = Infected[0], Removed[0]

# Os demais, S_start, são os indivíduos inicialmente suscetíveis.
S_start = N - I_start - R_start

# Malha de pontos no tempo (em dias)
t = np.arange(0, 150, 1)

# Dias (data de início da simulação: 04 de Abril de 2020)
# este dia foi escolhido, pois nele começam a surgir casos removidos
ddays = pd.date_range(start='4/4/2020', periods=len(t))

dados.tail()
```

      Dias
      Confirmados
      Recuperados
      Mortos

      31
      05/05/20
      1931
      557
      55

      32
      06/05/20
      2046
      596
      56

      33
      07/05/20
      2199
      612
      61

      34
      08/05/20
      2322
      640
      66

      35
      09/05/20
      2493
      665
      69

### Função para minização
Esta função `loss` é utilizada para fazer a minimização do problema de valor inicial e posteriormente encontrar os parâmetros que melhor ajustam os dados importados.

```python
def loss(point, data, removed, s_0, i_0, r_0, N):
    size = len(data)
    beta, gamma = point
    def SIR(t, y):
        S = y[0]
        I = y[1]
        R = y[2]
        return [-beta*S*I/N, beta*S*I/N-gamma*I, gamma*I]
    solution = solve_ivp(SIR, [0, size], [s_0,i_0,r_0], t_eval=np.arange(0, size, 1), vectorized=True)
    # the root mean squared error (RMSE) - a raiz do erro quadrado médio
    l1 = np.sqrt(np.mean((solution.y[1] - data)**2))
    l2 = np.sqrt(np.mean((solution.y[2] - removed)**2))
    alpha = 0.7 # ponderamento dos dados
    return alpha * l1 + (1 - alpha) * l2
```

### Cálculo do parâmetros

Os paramêtros $\beta$ (taxa contaminação) e $\gamma$ (taxa de recuperação), necessários para a construção da solução, são computados em cada intervalo de integração até a mais recente data. Os valores de $R_0$ (número básico de reprodução) e $p_{c}$ (índice de imunidade de rebanho) também serão calculados, a cada passo, para comparação.

A rotina `minimize` é utilizada para encontrar os parametros  $\beta$ e $\gamma$.

```python
beta, gamma = [], []

num_frames = 20 # num. de frames

for k in range(num_frames):
    optimal = minimize(loss, [0.001, 0.001], args=(Infected[:17+k], Removed[:17+k], S_start, I_start, R_start, N), method='L-BFGS-B', bounds=[(0.00000001, 0.7), (0.00000001, 0.7)])
    beta.append(optimal.x[0])
    gamma.append(optimal.x[1])

obj = {'Dia (Integração)': Dias[16:], 'beta': beta, 'gamma': gamma}
output = pd.DataFrame(data=obj)
output['R0'] = output['beta']/output['gamma']
output['Pc'] = 1-1/output['R0']

output.tail()

```

      Dia (Integração)
      beta
      gamma
      R0
      Pc

      31
      05/05/20
      0.213241
      0.086808
      2.456458
      0.592910

      32
      06/05/20
      0.207125
      0.080530
      2.572029
      0.611202

      33
      07/05/20
      0.201409
      0.074996
      2.685581
      0.627641

      34
      08/05/20
      0.196418
      0.070668
      2.779459
      0.640218

      35
      09/05/20
      0.191712
      0.066728
      2.873033
      0.651936

### As equações do modelo SIR
Abaixo estão definidas o conjunto das 3 equações acopladas que descrevem o comportamento epidemiológico.

\begin{equation}
S'(t) = -\beta \dfrac{I(t)}{N(t)}S(t); \quad I'(t) = \beta \dfrac{I(t)}{N(t)}S(t) - \gamma I(t) \quad \mbox{e}\quad
R'(t) = \gamma I(t)
\end{equation}

```python
# As equações diferenciais do modelo SIR
def deriv(t, y, N, beta, gamma):
    S, I, R = y
    dSdt = -beta * S * I / N
    dIdt = beta * S * I / N - gamma * I
    dRdt = gamma * I
    return dSdt, dIdt, dRdt
```

### Solução numérica do modelo
A solução numérica do modelo é aprensentada em seguida, utilizando a biblioteca voltada para equações diferenciais `solve_ivp` em problemas de valor inicial. A cada passo de tempo, as soluções são gravadas nas linhas das matrizes `S`, `I` e `R`.

```python
# Initial conditions vector
y0 = S_start, I_start, R_start

# Set init values
S, I, R = [], [], []
Imax, Ixmax = [], []

for i in range(num_frames):
    sol = solve_ivp(deriv, [0, len(t)], y0, vectorized=True, args=(N, beta[i], gamma[i]), t_eval=t)
    # Integrate the SIR equations over the time grid, t.
    S.append(sol.y[0])
    I.append(sol.y[1])
    R.append(sol.y[2])

    Imax.append(max(I[i]))
    Ixmax.append(np.argmax(I[i]))

# Month abbreviation, day and year
d1 = ddays[Ixmax[-1]].strftime("%d %b %Y")

print('No dia ', d1, 'é atingido o número máximo de infectados: ', int(Imax[-1]))
```

    No dia  02 Jul 2020 é atingido o número máximo de infectados:  241112

### Criar frames
Nesta seção são criados os frames para cada uma das soluções

```python
frames = []
for frame in range(num_frames):
    x_axis_frame = ddays
    y_axis_frameS = S[frame]
    y_axis_frameI = I[frame]
    y_axis_frameR = R[frame]
    curr_frame = go.Frame(data = [go.Scatter(x = x_axis_frame, y = y_axis_frameS, mode = 'lines' ),
                                  go.Scatter(x = x_axis_frame, y = y_axis_frameI, mode = 'lines' ),
                                  go.Scatter(x = x_axis_frame, y = y_axis_frameR, mode = 'lines' )])
    frames.append(curr_frame)
```

### Criar Figura
Este é o último passo para a visualização das soluções. A figura é criada colocando a solução inicial, de onde partem as demais soluções. Os frames criados anteriormente são acrescentados, a fim de vizualizar as soluções a cada passo de tempo.

```python
figure = go.Figure(
    data = [go.Scatter(x = ddays, y = S[0], mode = 'lines', name = "Sucetíveis", line = dict(color='rgb(20, 158, 217)')),
            go.Scatter(x = ddays, y = I[0], mode = 'lines', name = "Infectados", line = dict(color='rgb(227, 50, 88)')),
            go.Scatter(x = ddays, y = R[0], mode = 'lines', name = "Removidos", line = dict(color='rgb(0, 153, 137)'))], # list of traces
    layout = {
        # "title": "Simulação do modelo Epidêmico SIR",
        "hovermode":"x",
        "legend": {"x":0.2, "y":1.1},
        "legend_orientation": "h",
        "plot_bgcolor": 'rgba(10,10,10,0)',
        "margin":{"t":50, "b":0, "l":0, "r":0},
        "updatemenus":[{
            "type":"buttons",
            "direction": "left",
            "pad":{"b":10, "t":10,  "l":0},
            "x":0.0,
            "xanchor":"left",
            "y":-0.2,
            "yanchor":"bottom",
            "buttons":[{
                "label": "Play",
                "method": "animate",
                "args": [None, {'frame': {'duration': 1000, 'redraw': True}, "fromcurrent": True, 'transition': {'duration': 10, 'easing': 'linear'}}]
            },
            {
                'label': 'Pause',
                'args': [[None], {'frame': {'duration': 0, 'redraw': False}, 'mode': 'immediate',
                'transition': {'duration': 0}}],
                'method': 'animate'
            }],
        }],
        "xaxis": {"range": [ddays[0],ddays[-1]], "showspikes": True, "spikemode": "toaxis+marker"},
        "yaxis": {"range": [0,N], "title": "População", "side":"right", "showgrid": True, "gridwidth": 1, "gridcolor":"#B6B6B6"}
    },
    frames = frames
)

figure.show()
```

No gráfico animado acima é possível ter uma noção de como a doença pode evoluir nos próximos meses. A animação aprensenta o comportamento das curvas de infectados, removidos (mortos + recuperados) e suscetíveis, levando em conta os últimos 20 dias até o dia 09 de maio.

O gráfico mostra que o pico de infectados pode ser atingido no início do mês de **Julho (02/07)** com mais de **241 mil pessoas infectadas**. Além disso, nota-se que o pico de infectados aumenta, apesar de se afastar ligeiramente.

Os valores de $\alpha$, $\beta$ e, consequentemente, $R_0$ e $p_c$ obtidos até a presente data são mostradas na tabela abaixo:

```python
output.tail(8)
figure.write_html("sir.html")
```

Olhando os valores do número de reprodução ($R_0$) na tabela acima, o que mais chama atenção é o seu aumento. O $R_0$ chega a atingir $2.87$, na data mais recente. Isso significa que uma única pessoa pode infectar por volta de $3$ outros indivíduos. Para que a doença seja controlada esse número precisa estar abaixo de $1$.

Com o aumento do número de reprodução, pode-se notar também que para atingir a imunidade de rebanho pelo menos $65\%$ ($p_c=0.65$ ) da população deve passar pela doença.

## Conclusões
Resolvi explicar um pouco do modelo, pois sua compreensão mostra a importância do distanciamento social. Como a Covid-19 ainda não possui vacina para achatar de vez a curva de infectados, a única forma de garantir que mais pessoas possam ter acesso a leitos em hospitais é reduzindo a taxa de transmissão ($\beta$) e isso só pode ser feito com o isolamento e distanciamento social.

As simulações realizadas coletando os dados do estado do Amapá mostram um cenário preocupante para os próximos meses. Apesar de apresentar um leve achatamento da curva no início da simulação, o aumento do pico da curva mostra um relaxamento nas medidas de isolamento pela população. Se o cenário apresentado se confirmar, o estado pode sofrer não somente um colapso de todo o sistema de saúde, mas um colapso do sistema funerário causado pelo alto número de mortes.

Apesar de o modelo mostrar um alto número de infectados, vale lembrar que nem todos os indivíduos manifestam  sintomas, mas mesmo assim podem espalhar a doença e acelerar o contágio, caso não realizem o autoisolemento. Além disso, nem todos os infectados precisarão de leitos clínicos ou de UTI. Pela última estimativa que realizei por meio do [Boletim de 09/04](https://www.portal.ap.gov.br/noticia/0905/boletim-informativo-covid-19-amapa-9-de-maio-de-2020), cerca $6,6\%$ dos infectados precisam de algum leito (clínico ou de UTI). Se este número se mantém, no pico da curva de infectados (cerca de 241.112 pessoas), seria necessário por volta de **15.900** leitos em todo o estado.

Pelo relatório divulado pela [*Imperial College London (report 21)*](https://www.imperial.ac.uk/mrc-global-infectious-disease-analysis/covid-19/report-21-brazil/) sobre o Brasil, no dia 08 de maio, a taxa de mortalidade por infecção do novo Coronavírus está entre $0.7\%$ e $1.2\%$. Se olharmos novamente para o pico de infectados da doença no Amapá esse número de óbitos pode chegar, por baixo, a **1.687** no estado (mesmo que não seja notificado), o que trás também o colapso funerário. Isso sem contar os mortos até que esse pico seja alcançado, que são incluídos como removidos nas simulações. Para minimizar o quantidade de pessoas sem atendimento médico e, consequentemente, o caos de mortos, a solução é "achatar a curva" de infectados e isso, repito, só será alcançado com um forte isolamento e distanciamento social.

Na presente data, o índice de isolamento social no Amapá, estimado pelo [Inloco](https://www.inloco.com.br/pt/), está próximo de $48\%$. O taxa ideal de isolamento é $70\%$, mas em todo país tem-se observado esse baixo índice. Com o pico da curva de infectados se aproximando de forma acelerada e os sistemas de saúde municipais e estadual a beira do colapso o cenário mais provável para as próximas semanas é a adoção, pelo governo e prefeituras, de decretos mais rigorosos em relação a circulação de pessoas.

## Aviso
A estimativa do modelo é bem simplificada, pois, pela própria construção, se considera uma população distribuida de forma homogênea (ideal) e sabe-se que isso não é o que ocorre. As pessoas estão agrupadas por cidades, bairros, comunidades, etc. Existem [modelos mais complexos](https://en.wikipedia.org/wiki/Compartmental_models_in_epidemiology) que podem considerar esse fatores.

Além disso, o modelo depende da correta notificação de casos infectados e isso não tem ocorrido. O estado do Amapá, assim como outros estados, sofre pela subnotificação e falta de exames. O Amapá ainda tem um agravante em relação aos demais estados, pois depende de exames realizados no [Instituto Evandro Chagas, em Belém-PA](https://www.portal.ap.gov.br/noticia/2403/governo-do-amapa-envia-4-ordf-remessa-de-casos-suspeitos-do-novo-coronavirus), que quando retornam (alguns dias depois) aumentam o notificação de casos Covid-19 naquele dia. Ou seja, não significa que os casos se confirmaram naquele dia, mas que foram notificados naquele dia. O mesmo acontece quando o estado recebe uma remessa grande de testes rápidos (IgG e IgM) e tira da fila os muitos casos suspeitos em um curto período.

Os boletins do governo apenas notificam a quantidade de casos acumulados naquele dia e não atualiza os dados pelo dia em que o exame foi coletado. Isso fica evidente quando o próprio [portal de estatísticas do governo](http://painel.corona.ap.gov.br/) usa os dados acumulados fornecidos pelos boletins diários. No quesito de precisão de dados, a contagem de mortos por Covid-19 talvez sejam mais precisos, mesmo que hajam casos de óbitos que não foram testados e óbitos em residências, que não entram nas estatísticas.

Mesmo que os dados da simulação não sejam os mais precisos e o modelo seja simplificado, a previsão do aumento do pico da curva é real e é provocado pela falta de cumprimentos das medidas de isolamento.

## Referências
1. [The SIR epidemic model in python](https://scipython.com/book/chapter-8-scipy/additional-examples/the-sir-epidemic-model/)
2. [The SIR model - Wikipedia](https://en.wikipedia.org/wiki/Compartmental_models_in_epidemiology#The_SIR_model)
3. [COVID-19 dynamics with SIR model](https://www.lewuathe.com/covid-19-dynamics-with-sir-model.html)
4. [Plotly](https://plotly.com/)

Agradecimentos
--------------

-   Um agradecimento especial ao **Prof. Dr. Fernando Rodrigues Oliveira
    (IFRS-Osório)**, um amigo e colega de trabalho, que me apresentou [este modelo](https://www.youtube.com/watch?v=1sySX-rGKWs) e possibilitou ricas discussões a respeito do tema.

```python
## Print dependences

%load_ext watermark

# Python, Ipython, packages, machine characteristics
%watermark -v -m -p numpy,matplotlib,plotly,pandas,scipy
```

    The watermark extension is already loaded. To reload it, use:
      %reload_ext watermark
    CPython 3.7.6
    IPython 7.12.0

    numpy 1.18.1
    matplotlib 3.1.3
    plotly 4.6.0
    pandas 1.0.1
    scipy 1.4.1
    datetime unknown

    compiler   : GCC 7.3.0
    system     : Linux
    release    : 4.15.0-99-generic
    machine    : x86_64
    processor  :
    CPU cores  : 12
    interpreter: 64bit