Skip to content

Commit

Permalink
comprehensive testing for the speed and accuracy of the determinant a…
Browse files Browse the repository at this point in the history
…nd inverse implementation of 2x2 matrices
  • Loading branch information
paulalndwhr committed Dec 31, 2023
1 parent 54e1432 commit 06762de
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
9 changes: 6 additions & 3 deletions src/doptics/triangle_mesh.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,12 @@ def inv_2x2(a: NDArray([2, 2])):
:param a:
:return:
"""
a_inv = np.array([[a[1, 1], -a[0, 1]],
[-a[1, 0], a[0, 0]]]
) / det_2x2(a)
det_a = det_2x2(a)
if det_a == 0:
raise ValueError(f"det(A) = 0 => Matrix {a} is not invertible")
return np.array([[a[1, 1], -a[0, 1]],
[-a[1, 0], a[0, 0]]]
) / det_2x2(a)


def transform(triangle: Triangle, target: Triangle = {'a': (0, 0), 'b': (1, 0), 'c': (0, 1)}):
Expand Down
31 changes: 31 additions & 0 deletions tests/test_triangle_mesh.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,44 @@
import numpy as np
from typing import Callable
from icecream import ic
import pytest
from time import perf_counter


def test_det_2x2():
"""
asserting that the direct implementation of the 2x2 determinant is close to the np.linalg.det() and that it is faster
:return:
"""
a = [np.random.rand(2, 2) for x in range(100)]
start_dir = perf_counter()
det_dir = [tm.det_2x2(x) for x in a]
end_dir = perf_counter()
det_np = [np.linalg.det(x) for x in a]
end_np = perf_counter()
np.testing.assert_allclose(det_dir, det_np)
assert end_np - end_dir > end_dir - start_dir


def test_inv_2x2():
"""
asserting that the direct implementation of the 2x2 inverse is close to the np.linalg.inv() and that it is faster.
Also asserts that an exception is raised appropriately if det(A) = 0 <=> the determinant cannot be calculated.
:return:
"""
a = [np.random.rand(2, 2) for x in range(100)]
start_dir = perf_counter()
inv_dir = [tm.inv_2x2(x) for x in a]
end_dir = perf_counter()
inv_np = [np.linalg.inv(x) for x in a]
end_np = perf_counter()
np.testing.assert_allclose(inv_dir, inv_np)
assert end_np - end_dir > end_dir - start_dir
# non-invertible
with pytest.raises(ValueError) as e:
x = tm.inv_2x2(np.zeros([2,2]))
assert str(e.value.args[0]) == "det(A) = 0 => Matrix [[0. 0.]\n [0. 0.]] is not invertible"
assert e.type is ValueError


def test_Triangles():
Expand Down

0 comments on commit 06762de

Please sign in to comment.