# Лабораторная работа 7. Алгоритмы сортировки и поиска.

# 1. Алгоритмы сортировки.

```python
ary = [0, 3, 5, 1, 2, 3, 5, 4, 2, 34, 43, 24]
```

# 1.1. Сортировка выбором

Алгоритм:
- найти наименьший элемент в неотсортированной части массива;
- поставить его в начало;
- сдвинуть начало неотсортированной части.

Сложность: $O(n^2)$.

Программа:

```python
def insertion_sort(arrayToSort):
    a = arrayToSort.copy()
    n = len(a)
    for i in range(n):
        v = a[i]
        j = i
        while (a[j - 1] > v) and (j > 0):
            a[j] = a[j - 1]
            j = j - 1
        a[j] = v
    return a
```

Тестовый запуск:

```python
print(insertion_sort(ary))
```

    [0, 1, 2, 2, 3, 3, 4, 5, 5, 24, 34, 43]

# 1.2. Сортировка вставками

Алгоритм:
- из неотсортированной части берется элемент;
- вставляется в отсортированную часть на своё место (в начале массива).

Сложность: $O(n^2)$.

```python
def insertion_sort(arrayToSort):
    a = arrayToSort.copy()
    n = len(a)
    for i in range(n):
        v = a[i]
        j = i
        while (a[j-1] > v) and (j > 0):
            a[j] = a[j-1]
            j = j - 1
        a[j] = v
    return a
```

```python
print(insertion_sort(ary))
```

    [0, 1, 2, 2, 3, 3, 4, 5, 5, 24, 34, 43]

# 1.3. Сортировка методом пузырька

Алгоритм:
- последовательно сравниваются пары элементов идущих друг за другом;
- в случае несоответствия выбранному порядку меняются местами.

Сложность: $O(n^2)$.

```python
def bubble_sort(arrayToSort):
    a = arrayToSort.copy()
    n = len(a)
    for i in range(n,0,-1):
        for j in range(1, i):
            if a[j-1] > a[j]:
                tmp = a[j-1]
                a[j-1] = a[j]
                a[j] = tmp
    return a
```

```python
print(bubble_sort(ary))
```

    [0, 1, 2, 2, 3, 3, 4, 5, 5, 24, 34, 43]

# 1.4. Сортировка слиянием

Алгоритм:
- сортируемый массив разбивается на две части примерно одинакового размера;
- каждая из получившихся частей сортируется отдельно, например — тем же самым алгоритмом;
- два упорядоченных массива половинного размера соединяются в один.

Сложность: $O(n^2)$.

```python
def merge_sort(arrayToSort):
    if len(arrayToSort) > 1:
        mid = len(arrayToSort) // 2
        lefthalf = arrayToSort[:mid]
        righthalf = arrayToSort[mid:]

        merge_sort(lefthalf)
        merge_sort(righthalf)

        i, j, k = 0, 0, 0
        while i < len(lefthalf) and j < len(righthalf):
            if lefthalf[i] < righthalf[j]:
                arrayToSort[k] = lefthalf[i]
                i = i + 1
            else:
                arrayToSort[k] = righthalf[j]
                j = j + 1
            k = k + 1
        while i < len(lefthalf):
            arrayToSort[k] = lefthalf[i]
            i = i + 1
            k = k + 1
        while j < len(righthalf):
            arrayToSort[k] = righthalf[j]
            j = j + 1
            k = k + 1
```

```python
alist = ary
merge_sort(alist);
print(alist)
```

    [0, 1, 2, 2, 3, 3, 4, 5, 5, 24, 34, 43]

# 1.5. Быстрая сортировка

Алгоритм:
- выбрать (опорным) элемент из массива;
- перераспределить элементы в массиве так, что элементы меньше опорного помещаются перед ним, а больше или равные после;
- применить первые два шага к подмассивам слева и справа от опорных элементов, пока в подмассивах не останется не более одного элемента.

Сложность: cредняя — $O(n log_2 n)$, худшая — $O(n^2)$.

```python
def quick_sort(a, l, r):
    if (r > l):
        v, i, j = a[r], l - 1, r
        while (True):
            i, j = i + 1, j - 1
            while(a[i] < v): i = i + 1
            while(a[j] > v): j = j - 1
            if (i >= j): break
            a[i], a[j] = a[j], a[i]
        a[i], a[r] = a[r], a[i]
        quick_sort(a, l, i - 1)
        quick_sort(a, i + 1, r)
```

```python
alist = ary
quick_sort(alist, 0, len(alist)-1)
print(ary)
```

    [0, 1, 2, 2, 3, 3, 4, 5, 5, 24, 34, 43]

# Упражнение 1. Сортировка подсчётом.

Есть ли алгоритмы сортировки со сложностью, меньшей $O(n log_2 n)$?

Да, если известны свойства ключей. Например, если число возможных вариантов значений ограничено (и невелико) можно воспользоваться сортировкой подсчётом.

Алгоритм:
- создать массив с числом эллементов равным количеству возможным вариантов ключа, заполнить его 0;
- перебрать (пройти) сортируемое множество подсчитывая количество ключей с конкретным значением (увеличивая на 1 значения соответствующего эллемента ранее созданного массива);
- записать подряд все ненулевые эллементы получившегося массива соответствующее его значению число раз.

Сложность: $O(n+k)$, где $k$ - число вариантов ключей.

Напишите программу (функцию) реализующую данный алгоритм.

```python
# Так можно добавлять картинки

from IPython.display import Image # вызов из библиотеки определённой функции
Image("Сортировка подсчётом.png")              # вызов функции и передача ей в качестве аргумента пути к файлу

# (в данном случае фаил находится в той же папке)
```

```python
import numpy as np

def counterSort(S):
    F = np.zeros(max(S) + 1)
    for si in S:
        F[si] += 1
    j = 0
    for i in range(len(F)):
        if F[i] != 0:
            for k in range(int(F[i])):
                S[j] = i
                j += 1
    return S
```

```python
S = [10, 5, 14, 7, 3, 2, 18, 4, 5, 13, 6, 8]
print(counterSort(S))
```

    [2, 3, 4, 5, 5, 6, 7, 8, 10, 13, 14, 18]

# Пример. Число $\pi$

```python
from sympy import *
import numpy as np
import time
import pylab
import matplotlib.pyplot as plt
```

```python
# Выведем заданное колличество знаков числа pi
npi=7;
print('Выведем %i знаков числа пи:\n' %npi, pi.n(npi));
```

    Выведем 7 знаков числа пи:
     3.141593

Конвертируем дробную часть числа $\pi$ в список:

```python
PI = [int(i) for i in str(pi.n(npi))[2:]]
```

```python
PI
```

    [1, 4, 1, 5, 9, 3]

Кроме того, можем считать цифры дробной части числа $\pi$ из файла (в котором храняться 10 000 000 его символов):

```python
f = open("pi-10million.txt")  #  открываем файл
fs = f.readline(npi)          #  считываем из него npi символов
f.close()                     #  закроем файл
```

```python
fs
```

```python
Pi = [int(i) for i in fs]
print(Pi)
```

# Упражнение 2. Сортировка $\pi$

Сравните временную сложность всех рассмотренных алгоритмов сортировки на примере цифр числа $\pi$.

Воспользуйтесь для этого замером времени с помощью библиотеки `time`. Пример:

```python
start_time = time.time()
PI2 = insertion_sort(PI)
Time = time.time() - start_time
print ('Отсортированные цифры числа пи:', PI2, sep = '\n')
print('Время, потраченное на сортировку, составило %15.7e секунд' % Time)
```

    Отсортированные цифры числа пи:
    [1, 1, 3, 4, 5, 9]
    Время, потраченное на сортировку, составило   2.1815300e-04 секунд

Запишем отсортированный список в файл:

```python
f1 = open("pi_sort.txt", 'w')
f1.writelines('%i' % i for i in PI2)
f1.close()
```

Проверим, что получилось:

```python
f1 = open("pi_sort.txt", 'r')
fs = f1.readlines()          #  считываем всё содержимое файла
print(fs)
f1.close()
```

    ['113459']

Посмотрим, как меняются затраты времени на сортировку вставками при увеличении числа сортируемых объектов:

```python
ik = 11
Tame = np.zeros((3,ik))
NPI = [(i+1)*50 for i in range(ik)]
i=0
for npi in NPI:
    PI = [int(i) for i in str(pi.n(npi))[2:]]
    start_time = time.time()
    PI2 = insertion_sort(PI)
    Tame[0, i]=time.time()-start_time

    start_time = time.time()
    PI2 = insertion_sort(PI)
    Tame[1, i]=time.time()-start_time

    start_time = time.time()
    PI2 = insertion_sort(PI)
    Tame[2, i]=time.time()-start_time
    i+=1
```

```python
print('\t size\t Tame(sec)')
for i in range(0,ik):
    print ('\t %i \t %.3e' %(NPI[i], Tame[(0,i)]))
for i in range(0,ik):
    print ('\t %i \t %.3e' %(NPI[i], Tame[(1,i)]))
for i in range(0,ik):
    print ('\t %i \t %.3e' %(NPI[i], Tame[(2,i)]))

# график функции
pylab.figure ()
plt.plot(NPI, Tame[0], c='b')
plt.scatter(NPI, Tame[0], c='b',s=50)
plt.plot(NPI, Tame[1], c='b')
plt.scatter(NPI, Tame[1], c='b',s=50)
plt.plot(NPI, Tame[2], c='b')
plt.scatter(NPI, Tame[2], c='b',s=50)
# параметры графика
xl = plt.xlabel("size");
yl = plt.ylabel("tame (sec)");
plt.grid(True);
plt.show();
```

# Пример. Последовательный поиск

```python
def dummy_search(a, key):
    n = len(a)
    for i in range(n):
        if a[i] == key:
            return i
    return n
```

```python
ary = [7, 8, 1, 2, 3, 4, 13, 5, 1, 2, 44, 5, 1]
print(dummy_search(ary, 13))
```

    6

```python
# вероятно, чуть более рациональная реализация
def clever_search(a, key):
    n = len(a)
    i = 0
    while a[i] != key:
        i = i + 1
    return i
```

```python
ary2 = [7, 8, 1, 2, 3, 4, 13, 5, 1, 2, 44, 5, 1, 44]
print(clever_search(ary2, 13))
```

    6

```python
%timeit dummy_search(ary, 44)
%timeit clever_search(ary2, 44)
```

    3.05 µs ± 364 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
    2.71 µs ± 155 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

# Упражнение 3. Поиск в $\pi$

Найдите в дробной части числа $\pi$ порядковый номер каждой цифры, начиная с единицы, встретившейся `n`-ное количество раз, равное её значению (первую единицу, вторую двойку и т.д.).

```python
npi = 100
PI = [int(i) for i in str(pi.n(npi))[2:]]

a = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
k = a.copy()

for i in range(npi - 2):
    a[PI[i]] += 1
    if PI[i] == a[PI[i]]:
        k[PI[i]] = i + 1

print(k)
```

    [0, 1, 16, 17, 36, 48, 72, 96, 74, 55]

# Домашнее задание (базовое):

# Задание 1.

Найдите в числе $\pi$ номер цифры в дробной части, после которой идёт последовательность из:

- шести 9;
- шести 8;
- шести 0;
- первых шести цифр;
- семи цифр вашего номера телефона.

```python
from sympy import *
import numpy as np

npi = 300000
PI = [int(i) for i in str(pi.n(npi))[2:]]
```

```python
for i in range(npi - 7):
    if PI[i + 1 : i + 7] == [9, 9, 9, 9, 9, 9]:
        print(i)
        break
```

    760

```python
for i in range(npi - 7):
    if PI[i + 1 : i + 7] == [8, 8, 8, 8, 8, 8]:
        print(i)
        break
```

    222297

Файл с 4 млн цифр числа Пи после запятой можно найти по [ссылке](https://sanstv.ru/pi).

```python
f1 = open("pi.txt", 'r')
npi = 3999998
PIs = f1.readlines()
f1.close()
PI = []
for part in PIs:
    for n in part:
        if n != '.' and n != '\n':
            PI.append(int(n))
```

```python
for i in range(npi - 7):
    if PI[i + 1 : i + 7] == [0, 0, 0, 0, 0, 0]:
        print(i)
        break
```

    1699926

```python
for i in range(npi - 7):
    if PI[i + 1 : i + 7] == [1, 2, 3, 4, 5, 6]:
        print(i)
        break
```

    2458884

```python
for i in range(npi - 7):
    if PI[i + 1 : i + 8] == [1, 9, 3, 2, 6, 1, 1]:
        print(i)
        break
```

    431

# Задание 2. Поиск в отсортированном массиве

Реализуйте алгоритмы сужения области:

- [бинарный поиск](https://ru.wikipedia.org/wiki/%D0%94%D0%B2%D0%BE%D0%B8%D1%87%D0%BD%D1%8B%D0%B9_%D0%BF%D0%BE%D0%B8%D1%81%D0%BA)
- [метод золотого сечения](https://ru.wikipedia.org/wiki/%D0%9C%D0%B5%D1%82%D0%BE%D0%B4_%D0%B7%D0%BE%D0%BB%D0%BE%D1%82%D0%BE%D0%B3%D0%BE_%D1%81%D0%B5%D1%87%D0%B5%D0%BD%D0%B8%D1%8F)
- [интерполирующий поиск](https://ru.wikipedia.org/wiki/%D0%98%D0%BD%D1%82%D0%B5%D1%80%D0%BF%D0%BE%D0%BB%D1%8F%D1%86%D0%B8%D0%BE%D0%BD%D0%BD%D1%8B%D0%B9_%D0%BF%D0%BE%D0%B8%D1%81%D0%BA).

```python
def binarySearch(S, key):
    l = 0
    r = len(S) - 1
    while r - l > 1:
        m = (r + l) // 2
        if key > S[m]:
            l = m
        elif key < S[m]:
            r = m
        else:
            print('binarySearch:', m)
            return
            # важное пояснение: бинарный поиск не обязан искать первое вхождение,
            # потому что он с самого начала сравнивает с серединой
    if S[l] == key:
        print('binarySearch:', l)
    elif S[r] == key:
        print('binarySearch:', r)
    else:
        print('binarySearch: not found')
```

```python
def goldenCutSearch(S, key):
    phi = 0.5*(1 + 5 ** 0.5)
    a = 0
    b = len(S) - 1
    while b - a >= 1:
        x1 = int(b - (b - a)//phi)
        x2 = int(a + (b - a)//phi)
        A = S[a : x2 + 1]
        B = S[x1 : b + 1]
        if key in A:
            b = x2
        elif key in B:
            a = x1
        else:
            print('goldenCutSearch: not found')
            return
    print('goldenCutSearch:', a)
```

```python
def interpolationSearch(S, key):
    l = 0
    r = len(S) - 1
    while S[l] < key < S[r]:
        m = int(l + ((key - S[l]) * (r - l)) / (S[r] - S[l]))
        if key > S[m]:
            l = m + 1
        elif key < S[m]:
            r = m - 1
        else:
            print('interpolationSearch:', m)
            return
    if S[l] == key:
        print('interpolationSearch:', l)
    elif S[r] == key:
        print('interpolationSearch:', r)
    else:
        print('interpolationSearch: not found')
```

```python
S = list([7,8,1,2,3,4,13,5,1,2,44,5,1])
S.sort()
print(S)
```

    [1, 1, 1, 2, 2, 3, 4, 5, 5, 7, 8, 13, 44]

```python
M = [1, 3, 5, 7]
print(M)
```

    [1, 3, 5, 7]

```python
K = [1, 2, 3, 4, 5]
print(K)
```

    [1, 2, 3, 4, 5]

```python
U = [12.7, 9.1, 10.0012, 7.8]
U.sort()
print(U)
```

    [7.8, 9.1, 10.0012, 12.7]

```python
try:
    key = float(input('Введите значение ключа: '))
except ValueError:
    print('Вы ввели не число.')

A = list(map(float, input('Введите элементы массива через пробел: ').split()))

A.sort()
print('Отсортированный массив:', A, '\n')

print('Поиск:')
binarySearch(A, key)
goldenCutSearch(A, key)
interpolationSearch(A, key)
```

    Введите значение ключа: 83
    Введите элементы массива через пробел: 1 83 84 23 43 61
    Отсортированный массив: [1.0, 23.0, 43.0, 61.0, 83.0, 84.0]

    Поиск:
    binarySearch: 4
    goldenCutSearch: 4
    interpolationSearch: 4

# Задание 3.

Сравните производительность алгоритмов из задания 2 на задании 1.

```python
npi = 1000
PI = [int(i) for i in str(pi.n(npi))[2:]]
```

```python
D = {}
i = 0
for PI_i in PI:
    D[i] = PI_i
    i += 1
```

```python
PI = list(D.values())
```

```python
def dictionarySort(D):
    LOI = [] # list of indexes
    LOI = list(D.keys())

    # bubble sort method
    a = list(D.values())
    n = len(a)
    for i in range(n, 0, -1):
        for j in range(1, i):
            if a[j - 1] > a[j]:
                a[j - 1], a[j] = a[j], a[j - 1]
                LOI[j - 1], LOI[j] = LOI[j], LOI[j - 1]

    return LOI
```

```python
LOI = dictionarySort(D)
print(LOI)
```

    [31, 49, 53, 64, 70, 76, 84, 96, 105, 115, 120, 127, 131, 145, 158, 163, 166, 175, 194, 206, 244, 247, 263, 269, 286, 290, 306, 307, 310, 326, 329, 339, 356, 359, 360, 365, 368, 374, 397, 402, 407, 420, 442, 450, 492, 512, 519, 522, 542, 544, 551, 556, 560, 595, 600, 601, 602, 617, 637, 656, 658, 668, 681, 683, 702, 714, 719, 723, 745, 749, 754, 774, 780, 792, 801, 814, 817, 826, 837, 852, 854, 855, 856, 877, 884, 898, 908, 956, 967, 972, 973, 988, 995, 0, 2, 36, 39, 48, 67, 93, 94, 102, 109, 137, 147, 152, 153, 154, 162, 167, 173, 174, 197, 205, 219, 237, 242, 245, 249, 268, 280, 294, 296, 313, 318, 323, 341, 343, 361, 362, 380, 384, 389, 392, 394, 395, 416, 423, 426, 427, 431, 436, 437, 441, 444, 445, 470, 482, 489, 493, 494, 498, 524, 540, 546, 565, 567, 573, 586, 597, 606, 609, 626, 639, 645, 650, 659, 669, 680, 703, 708, 709, 711, 716, 727, 729, 733, 743, 751, 757, 758, 779, 785, 790, 796, 842, 845, 846, 849, 851, 853, 858, 881, 886, 888, 894, 920, 921, 944, 950, 960, 962, 970, 974, 982, 983, 984, 991, 996, 5, 15, 20, 27, 32, 52, 62, 72, 75, 82, 88, 92, 101, 111, 113, 134, 135, 139, 148, 159, 164, 172, 184, 185, 202, 220, 228, 240, 243, 259, 274, 279, 288, 291, 297, 301, 325, 328, 332, 334, 336, 353, 373, 379, 405, 422, 434, 455, 461, 476, 478, 483, 484, 499, 509, 523, 534, 535, 545, 557, 564, 570, 578, 599, 607, 612, 619, 629, 649, 660, 661, 686, 687, 693, 697, 701, 710, 712, 715, 736, 756, 770, 788, 802, 818, 821, 823, 824, 828, 840, 866, 876, 883, 903, 910, 926, 932, 959, 963, 964, 976, 990, 994, 8, 14, 16, 23, 24, 26, 42, 45, 63, 85, 90, 110, 114, 122, 136, 141, 169, 193, 195, 214, 215, 229, 230, 236, 260, 264, 273, 281, 282, 284, 299, 312, 345, 348, 357, 363, 364, 367, 381, 400, 401, 408, 419, 429, 433, 440, 456, 468, 487, 491, 502, 503, 506, 507, 518, 525, 531, 538, 554, 562, 572, 579, 598, 614, 627, 641, 643, 665, 667, 678, 698, 724, 734, 744, 759, 768, 784, 787, 795, 810, 816, 825, 830, 831, 838, 844, 857, 859, 862, 874, 875, 879, 897, 899, 905, 919, 929, 933, 935, 941, 958, 971, 1, 18, 22, 35, 56, 58, 59, 69, 86, 91, 103, 118, 124, 125, 144, 150, 156, 161, 181, 182, 187, 191, 200, 201, 216, 217, 222, 226, 250, 253, 261, 265, 270, 272, 277, 292, 295, 302, 320, 338, 347, 370, 375, 383, 385, 391, 399, 448, 452, 453, 463, 479, 496, 510, 511, 517, 527, 529, 536, 553, 581, 584, 588, 594, 610, 628, 651, 654, 655, 662, 666, 670, 673, 700, 722, 725, 726, 740, 760, 775, 803, 804, 807, 811, 820, 832, 833, 882, 895, 906, 909, 915, 993, 3, 7, 9, 30, 47, 50, 60, 89, 108, 129, 130, 132, 140, 142, 157, 171, 176, 177, 178, 190, 209, 212, 224, 239, 251, 255, 271, 303, 314, 315, 324, 337, 344, 354, 366, 369, 378, 388, 393, 403, 410, 412, 414, 418, 443, 447, 465, 469, 473, 475, 514, 533, 561, 577, 596, 603, 611, 615, 623, 631, 664, 672, 675, 677, 682, 694, 699, 706, 730, 750, 778, 781, 798, 800, 805, 808, 809, 822, 829, 836, 839, 865, 870, 873, 900, 904, 913, 914, 922, 924, 934, 939, 943, 946, 952, 957, 986, 6, 19, 21, 40, 68, 71, 74, 81, 97, 107, 116, 117, 126, 180, 183, 199, 210, 211, 218, 225, 233, 238, 252, 256, 257, 262, 267, 275, 276, 285, 289, 308, 309, 311, 331, 346, 349, 358, 376, 377, 386, 396, 409, 425, 435, 454, 460, 466, 504, 508, 513, 515, 516, 521, 530, 550, 569, 575, 582, 589, 591, 592, 604, 613, 616, 636, 642, 652, 671, 690, 707, 718, 721, 735, 748, 791, 794, 812, 819, 834, 841, 869, 885, 891, 892, 916, 925, 928, 965, 968, 969, 980, 981, 992, 12, 28, 38, 46, 55, 65, 95, 98, 119, 138, 155, 165, 208, 223, 231, 234, 241, 287, 298, 300, 305, 319, 342, 350, 404, 406, 411, 428, 438, 451, 457, 462, 467, 474, 477, 485, 505, 537, 539, 543, 547, 555, 558, 559, 566, 568, 574, 576, 583, 590, 608, 620, 621, 624, 625, 630, 632, 633, 640, 644, 646, 648, 679, 684, 688, 738, 739, 741, 742, 753, 755, 769, 772, 783, 786, 850, 860, 864, 872, 887, 889, 890, 896, 912, 918, 936, 938, 942, 947, 948, 953, 954, 961, 977, 979, 10, 17, 25, 33, 34, 51, 66, 73, 77, 80, 83, 87, 100, 104, 106, 112, 123, 133, 146, 149, 151, 160, 170, 188, 196, 203, 204, 221, 227, 232, 235, 254, 266, 278, 304, 316, 317, 321, 322, 333, 351, 371, 372, 382, 424, 430, 446, 449, 471, 472, 480, 488, 490, 501, 520, 549, 580, 585, 587, 605, 618, 622, 634, 647, 653, 676, 691, 695, 720, 728, 732, 752, 767, 773, 789, 797, 815, 827, 835, 847, 848, 861, 863, 867, 868, 871, 878, 880, 902, 911, 917, 927, 930, 931, 937, 949, 951, 955, 966, 978, 4, 11, 13, 29, 37, 41, 43, 44, 54, 57, 61, 78, 79, 99, 121, 128, 143, 168, 179, 186, 189, 192, 198, 207, 213, 246, 248, 258, 283, 293, 327, 330, 335, 340, 352, 355, 387, 390, 398, 413, 415, 417, 421, 432, 439, 458, 459, 464, 481, 486, 495, 497, 500, 526, 528, 532, 541, 548, 552, 563, 571, 593, 635, 638, 657, 663, 674, 685, 689, 692, 696, 704, 705, 713, 717, 731, 737, 746, 747, 761, 762, 763, 764, 765, 766, 771, 776, 777, 782, 793, 799, 806, 813, 843, 893, 901, 907, 923, 940, 945, 975, 985, 987, 989, 997, 998]

```python
def searchForOrderedSubsequences(S, length):
    subs = []
    for i in range(len(S) - length + 1):
        for k in range(1, length):
            if S[i + k] + 1 != S[i + k + 1]:
                break
            if k == length - 1:
                subs.append(i)
    return subs
```

```python
OSs = searchForOrderedSubsequences(LOI, 6)
for OS in OSs:
    print(LOI[OS + 1 : OS + 7])
```

    [761, 762, 763, 764, 765, 766]

```python
def sixNinesSearch(PI, D, OSs):
    PI.sort()
    for OS in OSs:
        if PI[OS + 1 : OS + 7] == [9, 9, 9, 9, 9, 9]:
            print('sixNinesSearch: found, index in original Pi number is', LOI[OS + 1] - 1)
```

```python
sixNinesSearch(PI, D, OSs)
```

    sixNinesSearch: found, index in original Pi number is 760

```python
def modifiedBinarySearch(PI, LOI, keySequence):
    l = 0
    r = len(LOI) - 1 - len(keySequence)
    PI.sort()
    while r - l > 1:
        m = (r + l) // 2
        if keySequence > PI[m + 1 : m + len(keySequence) + 1]:
            l = m
        elif keySequence < PI[m + 1 : m + len(keySequence) + 1]:
            r = m
        else:
            for k in range(1, len(keySequence)):
                if not LOI[m + k] + 1 == LOI[m + k + 1]:
                    l += 1
                    k = False
                    break
            if not k:
                continue
            print('modifiedBinarySearch:', LOI[m + 1] - 1)
            return
    print('modifiedBinarySearch: not found')
```

Поиск не работает в любом случае, имхо, так как он сдвигается только вправо, а нужно бы проходить по всей последовательности этих чисел + ко всему нижеприведенный код не найдёт там неупорядоченную строку, а также строку, содержащую цифры через один.

Статус: `задание не решено`.

```python
modifiedBinarySearch(PI, LOI, [9, 9, 9, 9, 9, 9])
```

    modifiedBinarySearch: 760

# Домашнее задание (дополнительное):

# Задание "Пирамидальная сортировка"

Напишите программу (функцию), реализующую алгоритм [пирамидальной сортировки](https://ru.wikipedia.org/wiki/%D0%9F%D0%B8%D1%80%D0%B0%D0%BC%D0%B8%D0%B4%D0%B0%D0%BB%D1%8C%D0%BD%D0%B0%D1%8F_%D1%81%D0%BE%D1%80%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%BA%D0%B0) (также есть [статья на Хабре](https://habr.com/ru/post/221095/) и книга "Алгоритмы. Справочник с примерами на C, C , Java и Python" (Хайнеман Дж., и др - 2017), с. 87).

```python
def heapSort(v):
    N = len(v)
    for j in range(N):
        for i in range(N // 2 - j // 2 - 1, -1, -1):
            if 2 * i + 2 <= N - 1 - j:
                if v[2 * i + 1] > v[2 * i + 2]:
                    if v[i] < v[2 * i + 1]:
                        v[i], v[2 * i + 1] = v[2 * i + 1], v[i]
                else:
                    if (v[i] < v[2 * i + 2]):
                        v[i], v[2 * i + 2] = v[2 * i + 2], v[i]
            else:
                if (2 * i + 1 <= N - 1 - j):
                    if (v[i] < v[2 * i + 1]):
                        v[i], v[2 * i + 1] = v[2 * i + 1], v[i]
        v[0], v[N - 1 - j] = v[N - 1 - j], v[0]
    for i in range(N):
        yield v[i]
```

```python
array = list(map(int, input('Введите элементы массива через пробел: ').split()))
sorted = [ str(i) for i in heapSort(array) ]
print('Отсортированный массив: ' + ' '.join(sorted))
```

    Введите элементы массива через пробел: 9 1 4 2
    Отсортированный массив: 1 2 4 9

```python
def heapify(arr, n, i):
    largest = i # Initialize largest as root
    l = 2 * i + 1   # left = 2*i + 1
    r = 2 * i + 2   # right = 2*i + 2
    if l < n and arr[i] < arr[l]:
        largest = l
    if r < n and arr[largest] < arr[r]:
        largest = r
    if largest != i:
        arr[i],arr[largest] = arr[largest],arr[i] # свап
        heapify(arr, n, largest)

def heapSort(arr):
    n = len(arr)
    for i in range(n, -1, -1):
        heapify(arr, n, i)
    for i in range(n-1, 0, -1):
        arr[i], arr[0] = arr[0], arr[i] # свап
        heapify(arr, i, 0)
```

```python
arr = [12, 11, 13, 5, 6, 7]
heapSort(arr)
```

```python
arr
```

    [5, 6, 7, 11, 12, 13]

Источник: [Хабр](https://habr.com/ru/company/otus/blog/460087/).

# Задание "Малые тела"

Есть база данных малых тел Солнечной системы, созданная под эгидой Международного астрономического союза. Файл с этой базой можно скачать [здесь](https://www.minorplanetcenter.net/iau/MPCORB/MPCORB.DAT), а [здесь](https://www.minorplanetcenter.net/iau/info/MPOrbitFormat.html) приведено его описание.

Отсортируйте эту базу по названию малого тела. Напишите две программы, реализующие поиск в отсортированном и неотсортированном массивах. В последнем случае поиск может производиться по любому параметру из таблицы.

```python
def sortByTitle(arr):
    return arr[2][23] # сортируем по строке

filename = input('Введите имя файла (по умолчанию - MPCORB.DAT): ')
if filename == '':
    filename = 'MPCORB.DAT'

data = [] # структура данных: индекс,
          #                   файловая строка,
          #                   [ структура в соответствии с описанием ]

with open(filename, 'r') as f:
    k = False
    i = 0
    for line in f:
        if '--------' in line:
            k = True
            continue
        if k:
            s = []
            s.append(line[0 : 7])
            s.append(line[8 : 13])
            s.append(float(line[14 : 19]))
            s.append(line[20 : 25])
            s.append(float(line[26 : 35]))
            s.append(float(line[37 : 46]))
            s.append(float(line[48 : 57]))
            s.append(float(line[59 : 68]))
            s.append(float(line[70 : 79]))
            s.append(float(line[80 : 91]))
            s.append(float(line[92 : 103]))
            s.append(line[105])
            s.append(line[107 : 116])
            s.append(int(line[117 : 122]))
            s.append(int(line[123 : 126]))
            s.append(int(line[127 : 131]))
            s.append(line[131])
            s.append(int(line[132 : 136]))
            s.append(line[137 : 141])
            s.append(line[142 : 145])
            s.append(line[146 : 149])
            s.append(line[150 : 160])
            s.append(line[161 : 165])
            s.append(line[166 : 194]) # тот самый кусок строки с названием объекта
            s.append(line[194 : 202])
            data.append([i, line, s])
            i += 1
    print('Прочитано и записано строк: %i' % i)

sorted_data = sorted(data, key=sortByTitle)
print('Сортировка завершена.')
```

```python
print('Прочитано и записано строк: %i' % i)
```

    Прочитано и записано строк: 545135

```python
sorted_data = sorted(data, key=sortByTitle)
print('Сортировка завершена.')
```

    Сортировка завершена.

```python
# поиск в несортированном массиве по имени малого тела
search_str = input('Введите строку поиска: ')
for i in range(len(data)):
    if search_str in data[i][2][23]:
        print('Совпадение в элементе %i несортированного массива. ' % i +
              'Планета - %s' % str(data[i][2][23]))
        print(data[i][1])
```

    Введите строку поиска: Hooveria
    Совпадение в элементе 931 несортированного массива. Планета -    (932) Hooveria
    00932   10.1   0.15 K205V 331.43567   50.02542   14.95652    8.11374  0.0905936  0.26190176   2.4194154  0 MPO525923  2385  39 1920-2020 0.39 M-v 38h Williams   0000    (932) Hooveria           20200106

```python
print(data[931][2][1], type(data[931][2][1]))
```

    10.1 <class 'float'>

```python
# поиск в отсортированном массиве по любому из 25 свойств,
# запись всех свойств в доп. массив
j = int(input('Введите один из 25 индексов данных (целое число от 1 до 25) ' +
              '(подробнее: https://www.minorplanetcenter.net/iau/info/' +
              'MPOrbitFormat.html): ')) - 1
search_str = input('Введите строку поиска: ')
selection = []
for i in range(len(sorted_data)):
    if type(sorted_data[i][2][j]) == type(str):
        if search_str in sorted_data[i][2][j]:
            print('Совпадение в элементе %i несортированного массива. ' % i +
                  'Значение - %s' % str(sorted_data[i][2][j]))
            print(sorted_data[i][1])
            selection.append(sorted_data[i])
    else:
        search_str = float(search_str)
        if search_str == sorted_data[i][2][j]:
            print('Совпадение в элементе %i несортированного массива. ' % i +
                  'Значение - %f' % float(sorted_data[i][2][j]))
            print(sorted_data[i][1])
            selection.append(sorted_data[i])
```

    Введите один из 25 индексов данных (целое число от 1 до 25) (подробнее: https://www.minorplanetcenter.net/iau/info/MPOrbitFormat.html): 14
    Введите строку поиска: 2625
    Совпадение в элементе 40 несортированного массива. Значение - 2625.000000
    00041    7.4   0.15 K205V 220.25379   45.93172  178.07248   15.78819  0.2750323  0.21480130   2.7612863  0 MPO525910  2625  63 1866-2020 0.47 M-v 38h Williams   0000     (41) Daphne             20200102

    Совпадение в элементе 107 несортированного массива. Значение - 2625.000000
    00108    8.0   0.15 K205V  42.16617  206.00387  349.97856    4.22024  0.0556404  0.16919836   3.2374665  0 MPO525911  2625  72 1880-2020 0.41 M-v 38h Williams   0000    (108) Hecuba             20200107

    Совпадение в элементе 206 несортированного массива. Значение - 2625.000000
    00207   10.1   0.15 K205V  73.72729  193.95481   29.17080    3.80172  0.0295908  0.28541617   2.2846359  0 MPO473763  2625  49 1885-2019 0.39 M-v 38h Williams   0000    (207) Hedda              20190510

    Совпадение в элементе 544 несортированного массива. Значение - 2625.000000
    00545    8.8   0.15 K205V 185.88366  330.95376  333.60048   11.20435  0.1698581  0.17195606   3.2027599  0 MPO525917  2625  46 1904-2020 0.39 M-v 38h Williams   0000    (545) Messalina          20200105

    Совпадение в элементе 1247 несортированного массива. Значение - 2625.000000
    01248    9.9   0.15 K205V 122.02568  344.59697   79.37822    9.13846  0.0165597  0.21958242   2.7210572  0 MPO525927  2625  45 1901-2020 0.39 M-v 38h Williams   0000   (1248) Jugurtha           20200109

    Совпадение в элементе 1381 несортированного массива. Значение - 2625.000000
    01382   12.1   0.15 K205V 196.76130  246.83837  353.00108    1.56142  0.1314277  0.29794981   2.2201074  0 MPO525929  2625  36 1925-2020 0.40 M-v 38h Williams   0000   (1382) Gerti              20200107

    Совпадение в элементе 3282 несортированного массива. Значение - 2625.000000
    03283   12.8   0.15 K205V 359.23420  352.50051  356.58768    6.89688  0.0999992  0.26567932   2.3964271  0 MPO525955  2625  28 1953-2019 0.42 M-v 38h Williams   0000   (3283) Skorina            20190915


```python
import control
from control.matlab import *
import numpy as np
import scipy as sc
import sympy as sy
import matplotlib.pyplot as plt
```

```python
def multiply_poly(a):
    p1 = np.array([1])
    for i in range(len(a)):
        polynom = np.array(a[i])
        p1 = sc.signal.convolve(p1, polynom)
    return p1
```

# Stability

## Routh-Hurwitz

```python
def print_pol(poly, degree):
    print("Polynom:")
    for i in range(degree+1):
        if i == degree:
            print(str(poly[i]),'\n')
        else:
            print(str(poly[i])+"s^"+str(degree-i), end ="+")

def fill_matrix(m, sz, degree):
    flag = 0
    for i in range(2):
        for j in range(sz):
            if i+2*j > degree:
                break
            m[i][j] = p[i+2*j]
    for i in range(2, degree+1):
        for j in range(sz-1):
            if m[i-1][0] == 0 and flag == 0:
                print("Caso especial uwu")
                m[i-1][0] = 1e-8
                flag = 1
            m[i][j] = (m[i-2][j+1]*m[i-1][0] - m[i-2][0]*m[i-1][j+1])/m[i-1][0]
        if flag == 1:
            flag = 2
            f = True
            for j in range(0, sz-1):
                if(m[i-1][j+1] != 0):
                    f = False
            if f:
                return i-1
    return -1

def special_case(m, pos, sz, degree):
    for i in range(sz):
        m[pos][i] = m[pos-1][i]*(degree-pos+1-2*i)
    for i in range(pos+1, degree+1):
        for j in range(sz-1):
            m[i][j] = (m[i-2][j+1]*m[i-1][0] - m[i-2][0]*m[i-1][j+1])/m[i-1][0]

def routh_hurwitz(p):
    degree = p.shape[0]-1
    sz = (degree+2)//2
    m = np.zeros((degree+1, sz))

    print_pol(p, degree)
    row = fill_matrix(m, sz, degree)
    if row == -1:
        print("Nice :)")
    else:
        print("Segundo caso especial uwu")
        special_case(m, row, sz, degree)

    print(m)
```

```python
#p = np.array([1,7,6,42,8,56])
p = np.array([1, 1, 12, 22, 39, 59, 48, 38, 20])

routh_hurwitz(p)
```

    Polynom:
    1s^8+1s^7+12s^6+22s^5+39s^4+59s^3+48s^2+38s^1+20

    Caso especial uwu
    Segundo caso especial uwu
    [[  1.          12.          39.          48.          20.        ]
     [  1.          22.          59.          38.           0.        ]
     [-10.         -20.          10.          20.           0.        ]
     [ 20.          60.          40.           0.           0.        ]
     [ 10.          30.          20.           0.           0.        ]
     [ 40.          60.           0.          -0.          -0.        ]
     [ 15.          20.           0.           0.           0.        ]
     [  6.66666667   0.          -0.          -0.           0.        ]
     [ 20.           0.           0.           0.           0.        ]]

# Steady-State errors

$$
E(s) = \frac{R(s)}{1+G(s)}
$$
$$
e(\infty) = \lim_{s\to 0} sE(s) = \lim_{s\to 0} \frac{sR(s)}{1+G(s)}
$$

```python
s, t = sy.symbols('s t')

def constants(G, R):
    e = sy.limit(s*R/(1+G), s, 0)
    kp = sy.limit(G, s, 0)
    kv = sy.limit(s*G, s, 0)
    ka = sy.limit(s*s*G, s, 0)
    print("e(oo) =", e)
    print("Kp =", kp)
    print("Kv =", kv)
    print("Ka =", ka)

G = 100*(s+2)*(s+6)/(s*(s+3)*(s+4))
R = sy.integrals.laplace_transform(5, t, s)[0]

constants(G, R)

R = sy.integrals.laplace_transform(5*t, t, s)[0]

constants(G, R)
```

    e(oo) = 0
    Kp = oo
    Kv = 100
    Ka = 0
    e(oo) = 1/20
    Kp = oo
    Kv = 100
    Ka = 0

```python

```


# Ridge and Lasso Regression

[Video of Lecture](https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureSeptember10.mp4?vrtx=view-as-webpage)

## The singular value decomposition

The examples we have looked at so far are cases where we normally can
invert the matrix $\boldsymbol{X}^T\boldsymbol{X}$. Using a polynomial expansion as we
did both for the masses and the fitting of the equation of state,
leads to row vectors of the design matrix which are essentially
orthogonal due to the polynomial character of our model. Obtaining the inverse of the design matrix is then often done via a so-called LU, QR or Cholesky decomposition.

This may
however not the be case in general and a standard matrix inversion
algorithm based on say LU, QR or Cholesky decomposition may lead to singularities. We will see examples of this below.

There is however a way to partially circumvent this problem and also gain some insights about the ordinary least squares approach, and later shrinkage methods like Ridge and Lasso regressions.

This is given by the **Singular Value Decomposition** algorithm, perhaps
the most powerful linear algebra algorithm.  Let us look at a
different example where we may have problems with the standard matrix
inversion algorithm. Thereafter we dive into the math of the SVD.

One of the typical problems we encounter with linear regression, in particular
when the matrix $\boldsymbol{X}$ (our so-called design matrix) is high-dimensional,
are problems with near singular or singular matrices. The column vectors of $\boldsymbol{X}$
may be linearly dependent, normally referred to as super-collinearity.
This means that the matrix may be rank deficient and it is basically impossible to
to model the data using linear regression. As an example, consider the matrix

$$
\begin{align*}
\mathbf{X} & =  \left[
\begin{array}{rrr}
1 & -1 & 2
\\
1 & 0 & 1
\\
1 & 2  & -1
\\
1 & 1  & 0
\end{array} \right]
\end{align*}
$$

The columns of $\boldsymbol{X}$ are linearly dependent. We see this easily since the
the first column is the row-wise sum of the other two columns. The rank (more correct,
the column rank) of a matrix is the dimension of the space spanned by the
column vectors. Hence, the rank of $\mathbf{X}$ is equal to the number
of linearly independent columns. In this particular case the matrix has rank 2.

Super-collinearity of an $(n \times p)$-dimensional design matrix $\mathbf{X}$ implies
that the inverse of the matrix $\boldsymbol{X}^T\boldsymbol{X}$ (the matrix we need to invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this

$$
\begin{align*}
\boldsymbol{X} & =  \left[
\begin{array}{rr}
1 & -1
\\
1 & -1
\end{array} \right].
\end{align*}
$$

We see easily that  $\mbox{det}(\boldsymbol{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \times (-1) - 1 \times (-1) = 0$. Hence, $\mathbf{X}$ is singular and its inverse is undefined.
This is equivalent to saying that the matrix $\boldsymbol{X}$ has at least an eigenvalue which is zero.

If our design matrix $\boldsymbol{X}$ which enters the linear regression problem

$$
\begin{equation}
\boldsymbol{\beta}  =  (\boldsymbol{X}^{T} \boldsymbol{X})^{-1} \boldsymbol{X}^{T} \boldsymbol{y},
\label{_auto1} \tag{1}
\end{equation}
$$

has linearly dependent column vectors, we will not be able to compute the inverse
of $\boldsymbol{X}^T\boldsymbol{X}$ and we cannot find the parameters (estimators) $\beta_i$.
The estimators are only well-defined if $(\boldsymbol{X}^{T}\boldsymbol{X})^{-1}$ exits.
This is more likely to happen when the matrix $\boldsymbol{X}$ is high-dimensional. In this case it is likely to encounter a situation where
the regression parameters $\beta_i$ cannot be estimated.

A cheap  *ad hoc* approach is  simply to add a small diagonal component to the matrix to invert, that is we change

$$
\boldsymbol{X}^{T} \boldsymbol{X} \rightarrow \boldsymbol{X}^{T} \boldsymbol{X}+\lambda \boldsymbol{I},
$$

where $\boldsymbol{I}$ is the identity matrix.  When we discuss **Ridge** regression this is actually what we end up evaluating. The parameter $\lambda$ is called a hyperparameter. More about this later.

From standard linear algebra we know that a square matrix $\boldsymbol{X}$ can be diagonalized if and only it is
a so-called [normal matrix](https://en.wikipedia.org/wiki/Normal_matrix), that is if $\boldsymbol{X}\in {\mathbb{R}}^{n\times n}$
we have $\boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{X}^T\boldsymbol{X}$ or if $\boldsymbol{X}\in {\mathbb{C}}^{n\times n}$ we have $\boldsymbol{X}\boldsymbol{X}^{\dagger}=\boldsymbol{X}^{\dagger}\boldsymbol{X}$.
The matrix has then a set of eigenpairs

$$
(\lambda_1,\boldsymbol{u}_1),\dots, (\lambda_n,\boldsymbol{u}_n),
$$

and the eigenvalues are given by the diagonal matrix

$$
\boldsymbol{\Sigma}=\mathrm{Diag}(\lambda_1, \dots,\lambda_n).
$$

The matrix $\boldsymbol{X}$ can be written in terms of an orthogonal/unitary transformation $\boldsymbol{U}$

$$
\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T,
$$

with $\boldsymbol{U}\boldsymbol{U}^T=\boldsymbol{I}$ or $\boldsymbol{U}\boldsymbol{U}^{\dagger}=\boldsymbol{I}$.

Not all square matrices are diagonalizable. A matrix like the one discussed above

$$
\boldsymbol{X} = \begin{bmatrix}
1&  -1 \\
1& -1\\
\end{bmatrix}
$$

is not diagonalizable, it is a so-called [defective matrix](https://en.wikipedia.org/wiki/Defective_matrix). It is easy to see that the condition
$\boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{X}^T\boldsymbol{X}$ is not fulfilled.

## The SVD, a Fantastic Algorithm

However, and this is the strength of the SVD algorithm, any general
matrix $\boldsymbol{X}$ can be decomposed in terms of a diagonal matrix and
two orthogonal/unitary matrices.  The [Singular Value Decompostion
(SVD) theorem](https://en.wikipedia.org/wiki/Singular_value_decomposition)
states that a general $m\times n$ matrix $\boldsymbol{X}$ can be written in
terms of a diagonal matrix $\boldsymbol{\Sigma}$ of dimensionality $m\times n$
and two orthognal matrices $\boldsymbol{U}$ and $\boldsymbol{V}$, where the first has
dimensionality $m \times m$ and the last dimensionality $n\times n$.
We have then

$$
\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T
$$

As an example, the above defective matrix can be decomposed as

$$
\boldsymbol{X} = \frac{1}{\sqrt{2}}\begin{bmatrix}  1&  1 \\ 1& -1\\ \end{bmatrix} \begin{bmatrix}  2&  0 \\ 0& 0\\ \end{bmatrix}    \frac{1}{\sqrt{2}}\begin{bmatrix}  1&  -1 \\ 1& 1\\ \end{bmatrix}=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T,
$$

with eigenvalues $\sigma_1=2$ and $\sigma_2=0$.
The SVD exits always!

The SVD
decomposition (singular values) gives eigenvalues
$\sigma_i\geq\sigma_{i+1}$ for all $i$ and for dimensions larger than $i=p$, the
eigenvalues (singular values) are zero.

In the general case, where our design matrix $\boldsymbol{X}$ has dimension
$n\times p$, the matrix is thus decomposed into an $n\times n$
orthogonal matrix $\boldsymbol{U}$, a $p\times p$ orthogonal matrix $\boldsymbol{V}$
and a diagonal matrix $\boldsymbol{\Sigma}$ with $r=\mathrm{min}(n,p)$
singular values $\sigma_i\geq 0$ on the main diagonal and zeros filling
the rest of the matrix.  There are at most $p$ singular values
assuming that $n > p$. In our regression examples for the nuclear
masses and the equation of state this is indeed the case, while for
the Ising model we have $p > n$. These are often cases that lead to
near singular or singular matrices.

The columns of $\boldsymbol{U}$ are called the left singular vectors while the columns of $\boldsymbol{V}$ are the right singular vectors.

## Economy-size SVD

If we assume that $n > p$, then our matrix $\boldsymbol{U}$ has dimension $n
\times n$. The last $n-p$ columns of $\boldsymbol{U}$ become however
irrelevant in our calculations since they are multiplied with the
zeros in $\boldsymbol{\Sigma}$.

The economy-size decomposition removes extra rows or columns of zeros
from the diagonal matrix of singular values, $\boldsymbol{\Sigma}$, along with the columns
in either $\boldsymbol{U}$ or $\boldsymbol{V}$ that multiply those zeros in the expression.
Removing these zeros and columns can improve execution time
and reduce storage requirements without compromising the accuracy of
the decomposition.

If $n > p$, we keep only the first $p$ columns of $\boldsymbol{U}$ and $\boldsymbol{\Sigma}$ has dimension $p\times p$.
If $p > n$, then only the first $n$ columns of $\boldsymbol{V}$ are computed and $\boldsymbol{\Sigma}$ has dimension $n\times n$.
The $n=p$ case is obvious, we retain the full SVD.
In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy.

```
import numpy as np
# SVD inversion
def SVDinv(A):
    ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD).
    SVD is numerically more stable than the inversion algorithms provided by
    numpy and scipy.linalg at the cost of being slower.
    '''
    U, s, VT = np.linalg.svd(A)
#    print('test U')
#    print( (np.transpose(U) @ U - U @np.transpose(U)))
#    print('test VT')
#    print( (np.transpose(VT) @ VT - VT @np.transpose(VT)))
    print(U)
    print(s)
    print(VT)

    D = np.zeros((len(U),len(VT)))
    for i in range(0,len(VT)):
        D[i,i]=s[i]
    UT = np.transpose(U); V = np.transpose(VT); invD = np.linalg.inv(D)
    return np.matmul(V,np.matmul(invD,UT))

X = np.array([ [1.0, -1.0, 2.0], [1.0, 0.0, 1.0], [1.0, 2.0, -1.0], [1.0, 1.0, 0.0] ])
print(X)
A = np.transpose(X) @ X
print(A)
# Brute force inversion of super-collinear matrix
#B = np.linalg.inv(A)
#print(B)
C = SVDinv(A)
print(C)
```

The matrix $\boldsymbol{X}$ has columns that are linearly dependent. The first
column is the row-wise sum of the other two columns. The rank of a
matrix (the column rank) is the dimension of space spanned by the
column vectors. The rank of the matrix is the number of linearly
independent columns, in this case just $2$. We see this from the
singular values when running the above code. Running the standard
inversion algorithm for matrix inversion with $\boldsymbol{X}^T\boldsymbol{X}$ results
in the program terminating due to a singular matrix.

There are several interesting mathematical properties which will be
relevant when we are going to discuss the differences between say
ordinary least squares (OLS) and **Ridge** regression.

We have from OLS that the parameters of the linear approximation are given by

$$
\boldsymbol{\tilde{y}} = \boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}.
$$

The matrix to invert can be rewritten in terms of our SVD decomposition as

$$
\boldsymbol{X}^T\boldsymbol{X} = \boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{U}^T\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T.
$$

Using the orthogonality properties of $\boldsymbol{U}$ we have

$$
\boldsymbol{X}^T\boldsymbol{X} = \boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}\boldsymbol{V}^T =  \boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T,
$$

with $\boldsymbol{D}$ being a diagonal matrix with values along the diagonal given by the singular values squared.

This means that

$$
(\boldsymbol{X}^T\boldsymbol{X})\boldsymbol{V} = \boldsymbol{V}\boldsymbol{D},
$$

that is the eigenvectors of $(\boldsymbol{X}^T\boldsymbol{X})$ are given by the columns of the right singular matrix of $\boldsymbol{X}$ and the eigenvalues are the squared singular values.  It is easy to show (show this) that

$$
(\boldsymbol{X}\boldsymbol{X}^T)\boldsymbol{U} = \boldsymbol{U}\boldsymbol{D},
$$

that is, the eigenvectors of $(\boldsymbol{X}\boldsymbol{X})^T$ are the columns of the left singular matrix and the eigenvalues are the same.

Going back to our OLS equation we have

$$
\boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y}.
$$

We will come back to this expression when we discuss Ridge regression.

$$ \tilde{y}^{OLS}=\boldsymbol{X}\hat{\beta}^{OLS}=\sum_{j=1}^p \boldsymbol{u}_j\boldsymbol{u}_j^T\boldsymbol{y}$$ and for Ridge we have

$$ \tilde{y}^{Ridge}=\boldsymbol{X}\hat{\beta}^{Ridge}=\sum_{j=1}^p \boldsymbol{u}_j\frac{\sigma_j^2}{\sigma_j^2+\lambda}\boldsymbol{u}_j^T\boldsymbol{y}$$ .

It is indeed the economy-sized SVD, note the summation runs up tp $$p$$ only and not $$n$$.

Here we have that $$\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T$$, with $$\Sigma$$ being an $$ n\times p$$ matrix and $$\boldsymbol{V}$$ being a $$ p\times p$$ matrix. We also have assumed here that $$ n > p$$.

## Ridge and LASSO Regression

[Video of Lecture](https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureSeptember11.mp4?vrtx=view-as-webpage)

Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is
our optimization problem is

$$
{\displaystyle \min_{\boldsymbol{\beta}\in {\mathbb{R}}^{p}}}\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}.
$$

or we can state it as

$$
{\displaystyle \min_{\boldsymbol{\beta}\in
{\mathbb{R}}^{p}}}\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2,
$$

where we have used the definition of  a norm-2 vector, that is

$$
\vert\vert \boldsymbol{x}\vert\vert_2 = \sqrt{\sum_i x_i^2}.
$$

By minimizing the above equation with respect to the parameters
$\boldsymbol{\beta}$ we could then obtain an analytical expression for the
parameters $\boldsymbol{\beta}$.  We can add a regularization parameter $\lambda$ by
defining a new cost function to be optimized, that is

$$
{\displaystyle \min_{\boldsymbol{\beta}\in
{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_2^2
$$

which leads to the Ridge regression minimization problem where we
require that $\vert\vert \boldsymbol{\beta}\vert\vert_2^2\le t$, where $t$ is
a finite number larger than zero. By defining

$$
C(\boldsymbol{X},\boldsymbol{\beta})=\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_1,
$$

we have a new optimization equation

$$
{\displaystyle \min_{\boldsymbol{\beta}\in
{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_1
$$

which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator.

Here we have defined the norm-1 as

$$
\vert\vert \boldsymbol{x}\vert\vert_1 = \sum_i \vert x_i\vert.
$$

Using the matrix-vector expression for Ridge regression,

$$
C(\boldsymbol{X},\boldsymbol{\beta})=\frac{1}{n}\left\{(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\right\}+\lambda\boldsymbol{\beta}^T\boldsymbol{\beta},
$$

by taking the derivatives with respect to $\boldsymbol{\beta}$ we obtain then
a slightly modified matrix inversion problem which for finite values
of $\lambda$ does not suffer from singularity problems. We obtain

$$
\boldsymbol{\beta}^{\mathrm{Ridge}} = \left(\boldsymbol{X}^T\boldsymbol{X}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y},
$$

with $\boldsymbol{I}$ being a $p\times p$ identity matrix with the constraint that

$$
\sum_{i=0}^{p-1} \beta_i^2 \leq t,
$$

with $t$ a finite positive number.

We see that Ridge regression is nothing but the standard
OLS with a modified diagonal term added to $\boldsymbol{X}^T\boldsymbol{X}$. The
consequences, in particular for our discussion of the bias-variance tradeoff
are rather interesting.

Furthermore, if we use the result above in terms of the SVD decomposition (our analysis was done for the OLS method), we had

$$
(\boldsymbol{X}\boldsymbol{X}^T)\boldsymbol{U} = \boldsymbol{U}\boldsymbol{D}.
$$

We can  analyse the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix $\boldsymbol{U}$ as

$$
\boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y}
$$

For Ridge regression this becomes

$$
\boldsymbol{X}\boldsymbol{\beta}^{\mathrm{Ridge}} = \boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T+\lambda\boldsymbol{I} \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\sum_{j=0}^{p-1}\boldsymbol{u}_j\boldsymbol{u}_j^T\frac{\sigma_j^2}{\sigma_j^2+\lambda}\boldsymbol{y},
$$

with the vectors $\boldsymbol{u}_j$ being the columns of $\boldsymbol{U}$.

Since $\lambda \geq 0$, it means that compared to OLS, we have

$$
\frac{\sigma_j^2}{\sigma_j^2+\lambda} \leq 1.
$$

Ridge regression finds the coordinates of $\boldsymbol{y}$ with respect to the
orthonormal basis $\boldsymbol{U}$, it then shrinks the coordinates by
$\frac{\sigma_j^2}{\sigma_j^2+\lambda}$. Recall that the SVD has
eigenvalues ordered in a descending way, that is $\sigma_i \geq
\sigma_{i+1}$.

For small eigenvalues $\sigma_i$ it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom.
Actually, calculating the variance of $\boldsymbol{X}\boldsymbol{v}_j$ shows that this quantity is equal to $\sigma_j^2/n$.
With a parameter $\lambda$ we can thus shrink the role of specific parameters.

For the sake of simplicity, let us assume that the design matrix is orthonormal, that is

$$
\boldsymbol{X}^T\boldsymbol{X}=(\boldsymbol{X}^T\boldsymbol{X})^{-1} =\boldsymbol{I}.
$$

In this case the standard OLS results in

$$
\boldsymbol{\beta}^{\mathrm{OLS}} = \boldsymbol{X}^T\boldsymbol{y}=\sum_{i=0}^{p-1}\boldsymbol{u}_j\boldsymbol{u}_j^T\boldsymbol{y},
$$

and

$$
\boldsymbol{\beta}^{\mathrm{Ridge}} = \left(\boldsymbol{I}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\left(1+\lambda\right)^{-1}\boldsymbol{\beta}^{\mathrm{OLS}},
$$

that is the Ridge estimator scales the OLS estimator by the inverse of a factor $1+\lambda$, and
the Ridge estimator converges to zero when the hyperparameter goes to
infinity.

We will come back to more interpreations after we have gone through some of the statistical analysis part.

For more discussions of Ridge and Lasso regression, [Wessel van Wieringen's](https://arxiv.org/abs/1509.09169) article is highly recommended.
Similarly, [Mehta et al's article](https://arxiv.org/abs/1803.08823) is also recommended.

## A better understanding of regularization

The parameter $\lambda$ that we have introduced in the Ridge (and
Lasso as well) regression is often called a regularization parameter
or shrinkage parameter. It is common to call it a hyperparameter. What does it mean mathemtically?

Here we will first look at how to analyze the difference between the
standard OLS equations and the Ridge expressions in terms of a linear
algebra analysis using the SVD algorithm. Thereafter, we will link
(see the material on the bias-variance tradeoff below) these
observation to the statisical analysis of the results. In particular
we consider how the variance of the parameters $\boldsymbol{\beta}$ is
affected by changing the parameter $\lambda$.

We have our design matrix
 $\boldsymbol{X}\in {\mathbb{R}}^{n\times p}$. With the SVD we decompose it as

$$
\boldsymbol{X} = \boldsymbol{U\Sigma V^T},
$$

with $\boldsymbol{U}\in {\mathbb{R}}^{n\times n}$, $\boldsymbol{\Sigma}\in {\mathbb{R}}^{n\times p}$
and $\boldsymbol{V}\in {\mathbb{R}}^{p\times p}$.

The matrices $\boldsymbol{U}$ and $\boldsymbol{V}$ are unitary/orthonormal matrices, that is in case the matrices are real we have $\boldsymbol{U}^T\boldsymbol{U}=\boldsymbol{U}\boldsymbol{U}^T=\boldsymbol{I}$ and $\boldsymbol{V}^T\boldsymbol{V}=\boldsymbol{V}\boldsymbol{V}^T=\boldsymbol{I}$.

## Introducing the Covariance and Correlation functions

Before we discuss the link between for example Ridge regression and the singular value decomposition, we need to remind ourselves about
the definition of the covariance and the correlation function. These are quantities

Suppose we have defined two vectors
$\hat{x}$ and $\hat{y}$ with $n$ elements each. The covariance matrix $\boldsymbol{C}$ is defined as

$$
\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{cov}[\boldsymbol{x},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\
                              \mathrm{cov}[\boldsymbol{y},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{y},\boldsymbol{y}] \\
             \end{bmatrix},
$$

where for example

$$
\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}).
$$

With this definition and recalling that the variance is defined as

$$
\mathrm{var}[\boldsymbol{x}]=\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})^2,
$$

we can rewrite the covariance matrix as

$$
\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{var}[\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\
                              \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] & \mathrm{var}[\boldsymbol{y}] \\
             \end{bmatrix}.
$$

The covariance takes values between zero and infinity and may thus
lead to problems with loss of numerical precision for particularly
large values. It is common to scale the covariance matrix by
introducing instead the correlation matrix defined via the so-called
correlation function

$$
\mathrm{corr}[\boldsymbol{x},\boldsymbol{y}]=\frac{\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}]}{\sqrt{\mathrm{var}[\boldsymbol{x}] \mathrm{var}[\boldsymbol{y}]}}.
$$

The correlation function is then given by values $\mathrm{corr}[\boldsymbol{x},\boldsymbol{y}]
\in [-1,1]$. This avoids eventual problems with too large values. We
can then define the correlation matrix for the two vectors $\boldsymbol{x}$
and $\boldsymbol{y}$ as

$$
\boldsymbol{K}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} 1 & \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] \\
                              \mathrm{corr}[\boldsymbol{y},\boldsymbol{x}] & 1 \\
             \end{bmatrix},
$$

In the above example this is the function we constructed using **pandas**.

In our derivation of the various regression algorithms like **Ordinary Least Squares** or **Ridge regression**
we defined the design/feature matrix $\boldsymbol{X}$ as

$$
\boldsymbol{X}=\begin{bmatrix}
x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\
x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\
x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\
\dots & \dots & \dots & \dots \dots & \dots \\
x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\
x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\
\end{bmatrix},
$$

with $\boldsymbol{X}\in {\mathbb{R}}^{n\times p}$, with the predictors/features $p$  refering to the column numbers and the
entries $n$ being the row elements.
We can rewrite the design/feature matrix in terms of its column vectors as

$$
\boldsymbol{X}=\begin{bmatrix} \boldsymbol{x}_0 & \boldsymbol{x}_1 & \boldsymbol{x}_2 & \dots & \dots & \boldsymbol{x}_{p-1}\end{bmatrix},
$$

with a given vector

$$
\boldsymbol{x}_i^T = \begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \dots & \dots x_{n-1,i}\end{bmatrix}.
$$

With these definitions, we can now rewrite our $2\times 2$
correaltion/covariance matrix in terms of a moe general design/feature
matrix $\boldsymbol{X}\in {\mathbb{R}}^{n\times p}$. This leads to a $p\times p$
covariance matrix for the vectors $\boldsymbol{x}_i$ with $i=0,1,\dots,p-1$

$$
\boldsymbol{C}[\boldsymbol{x}] = \begin{bmatrix}
\mathrm{var}[\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_1]  & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_{p-1}]\\
\mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_0] & \mathrm{var}[\boldsymbol{x}_1]  & \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_{p-1}]\\
\mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_0]   & \mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_1] & \mathrm{var}[\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_{p-1}]\\
\dots & \dots & \dots & \dots & \dots & \dots \\
\dots & \dots & \dots & \dots & \dots & \dots \\
\mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_0]   & \mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_{2}]  & \dots & \dots  & \mathrm{var}[\boldsymbol{x}_{p-1}]\\
\end{bmatrix},
$$

and the correlation matrix

$$
\boldsymbol{K}[\boldsymbol{x}] = \begin{bmatrix}
1 & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_1]  & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_2] & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_{p-1}]\\
\mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_0] & 1  & \mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_2] & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_{p-1}]\\
\mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_0]   & \mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_1] & 1 & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_{p-1}]\\
\dots & \dots & \dots & \dots & \dots & \dots \\
\dots & \dots & \dots & \dots & \dots & \dots \\
\mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_0]   & \mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_1] & \mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_{2}]  & \dots & \dots  & 1\\
\end{bmatrix},
$$

The Numpy function **np.cov** calculates the covariance elements using
the factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have
the exact mean values.  The following simple function uses the
**np.vstack** function which takes each vector of dimension $1\times n$
and produces a $2\times n$ matrix $\boldsymbol{W}$

$$
\boldsymbol{W} = \begin{bmatrix} x_0 & y_0 \\
                          x_1 & y_1 \\
                          x_2 & y_2\\
                          \dots & \dots \\
                          x_{n-2} & y_{n-2}\\
                          x_{n-1} & y_{n-1} &
             \end{bmatrix},
$$

which in turn is converted into into the $2\times 2$ covariance matrix
$\boldsymbol{C}$ via the Numpy function **np.cov()**. We note that we can also calculate
the mean value of each set of samples $\boldsymbol{x}$ etc using the Numpy
function **np.mean(x)**. We can also extract the eigenvalues of the
covariance matrix through the **np.linalg.eig()** function.

```
# Importing various packages
import numpy as np
n = 100
x = np.random.normal(size=n)
print(np.mean(x))
y = 4+3*x+np.random.normal(size=n)
print(np.mean(y))
W = np.vstack((x, y))
C = np.cov(W)
print(C)
```

The previous example can be converted into the correlation matrix by
simply scaling the matrix elements with the variances.  We should also
subtract the mean values for each column. This leads to the following
code which sets up the correlations matrix for the previous example in
a more brute force way. Here we scale the mean values for each column of the design matrix, calculate the relevant mean values and variances and then finally set up the $2\times 2$ correlation matrix (since we have only two vectors).

```
import numpy as np
n = 100
# define two vectors
x = np.random.random(size=n)
y = 4+3*x+np.random.normal(size=n)
#scaling the x and y vectors
x = x - np.mean(x)
y = y - np.mean(y)
variance_x = np.sum(x@x)/n
variance_y = np.sum(y@y)/n
print(variance_x)
print(variance_y)
cov_xy = np.sum(x@y)/n
cov_xx = np.sum(x@x)/n
cov_yy = np.sum(y@y)/n
C = np.zeros((2,2))
C[0,0]= cov_xx/variance_x
C[1,1]= cov_yy/variance_y
C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)
C[1,0]= C[0,1]
print(C)
```

We see that the matrix elements along the diagonal are one as they
should be and that the matrix is symmetric. Furthermore, diagonalizing
this matrix we easily see that it is a positive definite matrix.

The above procedure with **numpy** can be made more compact if we use **pandas**.

We whow here how we can set up the correlation matrix using **pandas**, as done in this simple code

```
import numpy as np
import pandas as pd
n = 10
x = np.random.normal(size=n)
x = x - np.mean(x)
y = 4+3*x+np.random.normal(size=n)
y = y - np.mean(y)
X = (np.vstack((x, y))).T
print(X)
Xpd = pd.DataFrame(X)
print(Xpd)
correlation_matrix = Xpd.corr()
print(correlation_matrix)
```

We expand this model to the Franke function discussed above.

```
# Common imports
import numpy as np
import pandas as pd

def FrankeFunction(x,y):
	term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))
	term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))
	term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))
	term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)
	return term1 + term2 + term3 + term4

def create_X(x, y, n ):
	if len(x.shape) > 1:
		x = np.ravel(x)
		y = np.ravel(y)

	N = len(x)
	l = int((n+1)*(n+2)/2)		# Number of elements in beta
	X = np.ones((N,l))

	for i in range(1,n+1):
		q = int((i)*(i+1)/2)
		for k in range(i+1):
			X[:,q+k] = (x**(i-k))*(y**k)

	return X

# Making meshgrid of datapoints and compute Franke's function
n = 4
N = 100
x = np.sort(np.random.uniform(0, 1, N))
y = np.sort(np.random.uniform(0, 1, N))
z = FrankeFunction(x, y)
X = create_X(x, y, n=n)

Xpd = pd.DataFrame(X)
# subtract the mean values and set up the covariance matrix
Xpd = Xpd - Xpd.mean()
covariance_matrix = Xpd.cov()
print(covariance_matrix)
```

We note here that the covariance is zero for the first rows and
columns since all matrix elements in the design matrix were set to one
(we are fitting the function in terms of a polynomial of degree $n$).

This means that the variance for these elements will be zero and will
cause problems when we set up the correlation matrix.  We can simply
drop these elements and construct a correlation
matrix without these elements.

We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix $\boldsymbol{X}$ as

$$
\boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}= \mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}].
$$

To see this let us simply look at a design matrix $\boldsymbol{X}\in {\mathbb{R}}^{2\times 2}$

$$
\boldsymbol{X}=\begin{bmatrix}
x_{00} & x_{01}\\
x_{10} & x_{11}\\
\end{bmatrix}=\begin{bmatrix}
\boldsymbol{x}_{0} & \boldsymbol{x}_{1}\\
\end{bmatrix}.
$$

If we then compute the expectation value

$$
\mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}=\begin{bmatrix}
x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\
x_{10}x_{00}+x_{11}x_{01} & x_{10}^2+x_{11}^2\\
\end{bmatrix},
$$

which is just

$$
\boldsymbol{C}[\boldsymbol{x}_0,\boldsymbol{x}_1] = \boldsymbol{C}[\boldsymbol{x}]=\begin{bmatrix} \mathrm{var}[\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_1] \\
                              \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_0] & \mathrm{var}[\boldsymbol{x}_1] \\
             \end{bmatrix},
$$

where we wrote $$\boldsymbol{C}[\boldsymbol{x}_0,\boldsymbol{x}_1] = \boldsymbol{C}[\boldsymbol{x}]$$ to indicate that this the covariance of the vectors $\boldsymbol{x}$ of the design/feature matrix $\boldsymbol{X}$.

It is easy to generalize this to a matrix $\boldsymbol{X}\in {\mathbb{R}}^{n\times p}$.

## Linking with SVD