aboutsummaryrefslogtreecommitdiff
path: root/test/test_solvers.py
blob: a7c175f8d5e7b548ed0ffce0f8cb8db8eb1255ed (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#!/usr/bin/env python3
"""Contains routines to test the solvers module"""

import numpy as np
from numpy.typing import NDArray

import solvers


def test_elimination_3() -> None:
    """Tests elimination with 3 variables."""
    aa = np.array([[2.0, 4.0, 4.0], [5.0, 4.0, 2.0], [1.0, 2.0, -1.0]], dtype=np.float_)
    bb = np.array([1.0, 4.0, 2.0], dtype=np.float_)
    xx_expected = np.array([0.666666666666667, 0.416666666666667, -0.5], dtype=np.float_)
    xx_gauss = solvers.gaussian_eliminate(aa, bb)
    assert np.allclose(xx_expected, xx_gauss)


def test_pivot_3() -> None:
    """Tests a solution with 3 variables, where pivot is necessary."""
    aa = np.array([[2.0, 4.0, 4.0], [1.0, 2.0, -1.0], [5.0, 4.0, 2.0]])
    bb = np.array([1.0, 2.0, 4.0])
    xx_expected = np.array([0.666666666666667, 0.416666666666667, -0.5])
    xx_gauss = solvers.gaussian_eliminate(aa, bb)
    assert np.allclose(xx_expected, xx_gauss)


def test_lindep_3() -> None:
    """Tests a linearly dependent system wit three variables."""
    aa = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]])
    bb = np.array([1.0, 2.0, 3.0])
    xx_expected = None
    xx_gauss = solvers.gaussian_eliminate(aa, bb)
    assert xx_expected == xx_gauss


def test_lu_factorization() -> None:
    aa = np.array([[2.0, 4.0, 4.0], [1.0, 2.0, -1.0], [5.0, 4.0, 2.0]])
    ll, uu, pp = solvers.lu_factorization(aa)
    assert np.allclose(aa, pp.T @ ll @ uu)


def test_forward_substitution() -> None:
    ll = np.array([[2.0, 0.0, 0.0], [-1.0, 2.0, 0.0], [4.0, 4.0, 2.0]])
    bb = np.array([3.0, 2.0, 1.0])
    xx_result = solvers.forward_substitution(ll, bb)
    xx_expected = np.array([3 / 2, 7.0 / 4.0, -6])
    print(xx_result)
    assert np.allclose(xx_expected, xx_result)

def test_back_substitution() -> None:
    uu = np.array([[2.0, 4.0, 4.0], [0.0, 2.0, -1.0], [0.0, 0.0, 2.0]])
    bb = np.array([1.0, 2.0, 3.0])
    xx_result = solvers.back_substitution(uu, bb)
    xx_expected = np.array([-6, 7.0 / 4.0, 3.0 / 2.0])
    print(xx_result)
    assert np.allclose(xx_expected, xx_result)