Compare commits

...
5 Commits
7 changed files with 276 additions and 5 deletions

No files matched your search

+8 -4
View File
@@ -1,5 +1,9 @@
# Regeln für dieses Projekt # Regeln für dieses Projekt
- Code nach PEP 8, Zeilenlänge maximal 88 Zeichen. - Code nach PEP 8, Zeilenlänge maximal 88 Zeichen.
- Jede Funktion und Methode hat einen Docstring und Type Hints. - Jede Funktion und Methode hat einen Docstring und Type Hints.
- Vor jedem Commit: `ruff check` und `ruff format`. - Vor jedem Commit: `ruff check` und `ruff format`.
## Projektstruktur
- Quellcode liegt unter "src/matrixmania/", Tests unter "test/test_matrixmania/"
- Testpakete, Testdateien und Testfunktionen beginnen mit "test_"
+7 -1
View File
@@ -1,4 +1,10 @@
[project] [project]
name = "matrixmania" name = "matrixmania"
version = "0.1.0" version = "0.1.0"
dependencies = ["tabulate", "ruff"] dependencies = ["tabulate", "ruff"]
[project.optional-dependencies]
dev = ["pytest", "ruff", "pytest-cov"]
[tool.pytest.ini_options]
pythonpath = "src"
+1
View File
@@ -0,0 +1 @@
from .compute import matmul, project_ortho, project_perspective, rot_2D, rot_3D, transpose
+110
View File
@@ -83,6 +83,107 @@ def rot_2D(angle: float) -> Matrix:
] ]
def rot_3D(angle: float, axis: str) -> Matrix:
"""
Liefert die Rotationsmatrix für eine Drehung um eine Koordinatenachse im 3D-Raum.
Rotation um die x-Achse:
Rx(θ) = [[1, 0, 0],
[0, cos θ, -sin θ],
[0, sin θ, cos θ]]
Rotation um die y-Achse:
Ry(θ) = [[ cos θ, 0, sin θ],
[ 0, 1, 0],
[-sin θ, 0, cos θ]]
Rotation um die z-Achse:
Rz(θ) = [[cos θ, -sin θ, 0],
[sin θ, cos θ, 0],
[ 0, 0, 1]]
Ein Punkt (x, y, z) wird gedreht, indem die Rotationsmatrix mit dem
Spaltenvektor [[x], [y], [z]] multipliziert wird.
:param angle: Drehwinkel θ im Bogenmaß
:param axis: Drehachse, entweder "x", "y" oder "z"
:return: Rotationsmatrix der Größe 3x3
:raises ValueError: Wenn axis nicht "x", "y" oder "z" ist
"""
cos_angle = math.cos(angle)
sin_angle = math.sin(angle)
if axis == "x":
return [
[1, 0, 0],
[0, cos_angle, -sin_angle],
[0, sin_angle, cos_angle],
]
if axis == "y":
return [
[cos_angle, 0, sin_angle],
[0, 1, 0],
[-sin_angle, 0, cos_angle],
]
if axis == "z":
return [
[cos_angle, -sin_angle, 0],
[sin_angle, cos_angle, 0],
[0, 0, 1],
]
raise ValueError(f"Ungültige Achse '{axis}', erlaubt sind 'x', 'y' oder 'z'")
def project_ortho(
point: tuple[float, float, float], scale: float = 1
) -> tuple[float, float]:
"""
Projiziert einen 3D-Punkt orthogonal auf die xy-Ebene.
Die z-Koordinate wird ignoriert, x und y werden mit scale skaliert:
(x, y, z) -> (x * scale, y * scale)
:param point: 3D-Punkt als Tupel (x, y, z)
:param scale: Skalierungsfaktor für den projizierten Punkt
:return: Projizierter 2D-Punkt als Tupel (x, y)
"""
x, y, _ = point
return x * scale, y * scale
def project_perspective(
point: tuple[float, float, float],
focal_length: float = 1.0,
scale: float = 1.0,
camera_distance: float = 4.0,
) -> tuple[float, float]:
"""
Projiziert einen 3D-Punkt perspektivisch auf die Bildschirmebene.
Weiter entfernte Punkte erscheinen kleiner, da x und y durch die Tiefe
des Punktes geteilt werden:
x' = x * focal_length / (z + camera_distance) * scale
y' = y * focal_length / (z + camera_distance) * scale
:param point: 3D-Punkt als Tupel (x, y, z)
:param focal_length: Brennweite, steuert die Stärke der Perspektive
:param scale: Skalierungsfaktor für den projizierten Punkt
:param camera_distance: Abstand der Kamera zum Ursprung entlang der z-Achse
:return: Projizierter 2D-Punkt als Tupel (x, y)
:raises ValueError: Wenn z + camera_distance kleiner oder gleich 0 ist,
der Punkt also auf Höhe der Kamera oder hinter ihr liegt
"""
x, y, z = point
depth = z + camera_distance
if depth <= 0:
raise ValueError(
f"Der Punkt liegt nicht vor der Kamera (z + camera_distance = {depth})"
)
factor = focal_length / depth * scale
return x * factor, y * factor
if __name__ == "__main__": if __name__ == "__main__":
matrix_a = [ matrix_a = [
[3, 4, -1, 4], [3, 4, -1, 4],
@@ -154,4 +255,13 @@ if __name__ == "__main__":
assert math.isclose(rotated_point[0][0], -2) assert math.isclose(rotated_point[0][0], -2)
assert math.isclose(rotated_point[1][0], -1) assert math.isclose(rotated_point[1][0], -1)
for axis in ("x", "y", "z"):
print(f"3D-Rotationsmatrix um die {axis}-Achse für 90°:")
print(tabulate(rot_3D(math.radians(90), axis)))
try:
rot_3D(1.0, "w")
except ValueError as error:
print(f"Erwarteter Fehler bei Achse 'w': {error}")
print("Alle Beispiele wurden erfolgreich geprüft.") print("Alle Beispiele wurden erfolgreich geprüft.")
View File
Whitespace-only changes.
+52
View File
@@ -0,0 +1,52 @@
import pytest
from matrixmania import project_ortho, project_perspective
def test_project_ortho_without_scale():
# Arrange
point = (1.0, 2.0, 3.0)
expected = (1.0, 2.0)
# Act
result = project_ortho(point)
# Assert
assert result == expected
def test_project_ortho_with_scale_100():
# Arrange
point = (1.0, 2.0, 3.0)
scale = 100
expected = (100.0, 200.0)
# Act
result = project_ortho(point, scale=scale)
# Assert
assert result == expected
def test_project_perspective_without_scale():
# Arrange
point = (1.0, 2.0, 3.0)
expected = (1 / 7, 2 / 7)
# Act
result = project_perspective(point, focal_length=1, scale=1)
# Assert
assert result == pytest.approx(expected)
def test_project_perspective_with_scale_100_and_focal_length_2():
# Arrange
point = (1.0, 2.0, 3.0)
expected = (200 / 7, 400 / 7)
# Act
result = project_perspective(point, focal_length=2, scale=100)
# Assert
assert result == pytest.approx(expected)
+98
View File
@@ -0,0 +1,98 @@
import math
import pytest
from matrixmania import matmul, rot_2D, rot_3D
def test_rot_2D_zero_angle_returns_identity():
# Arrange
angle = 0.0
expected = [[1.0, 0.0], [0.0, 1.0]]
# Act
result = rot_2D(angle)
# Assert
assert result == expected
def test_rot_2D_rotates_point_by_90_degrees():
# Arrange
angle = math.radians(90)
point = [[1], [0]]
expected = [0.0, 1.0]
# Act
result = [row[0] for row in matmul(rot_2D(angle), point)]
# Assert
assert result == pytest.approx(expected, abs=1e-9)
def test_rot_2D_rotates_point_by_180_degrees():
# Arrange
angle = math.pi
point = [[2], [1]]
expected = [-2.0, -1.0]
# Act
result = [row[0] for row in matmul(rot_2D(angle), point)]
# Assert
assert result == pytest.approx(expected, abs=1e-9)
@pytest.mark.parametrize("axis", ["x", "y", "z"])
def test_rot_3D_zero_angle_returns_identity(axis):
# Arrange
angle = 0.0
expected = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
# Act
result = rot_3D(angle, axis)
# Assert
assert result == expected
@pytest.mark.parametrize(
"axis, point, expected",
[
("x", [[0], [1], [0]], [0, 0, 1]),
("y", [[0], [0], [1]], [1, 0, 0]),
("z", [[1], [0], [0]], [0, 1, 0]),
],
)
def test_rot_3D_rotates_point_by_90_degrees(axis, point, expected):
# Arrange
angle = math.radians(90)
# Act
result = [row[0] for row in matmul(rot_3D(angle, axis), point)]
# Assert
assert result == pytest.approx(expected, abs=1e-9)
@pytest.mark.parametrize("axis", ["x", "y", "z"])
def test_rot_3D_returns_3x3_matrix(axis):
# Arrange
angle = 1.0
# Act
result = rot_3D(angle, axis)
# Assert
assert len(result) == 3
assert all(len(row) == 3 for row in result)
@pytest.mark.parametrize("invalid_axis", ["w", "", "X", "xy"])
def test_rot_3D_invalid_axis_raises_value_error(invalid_axis):
# Arrange
angle = 1.0
# Act / Assert
with pytest.raises(ValueError):
rot_3D(angle, invalid_axis)