Paketstruktur, rot_3D, Projektionen und pytest-Tests
- compute.py nach src/matrixmania verschoben, __init__.py exportiert die Funktionen - rot_3D, project_ortho und project_perspective ergänzt - Tests in test/test_matrixmania (test_rot.py, test_projection.py) - pyproject.toml: dev-Abhängigkeiten und pytest-pythonpath Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
892ec5e2c9
commit
7b8c76c554
9 files changed
+450
-3
No files matched your search
@@ -1,3 +1,4 @@
|
||||
.venv/
|
||||
__pycache__/
|
||||
.env
|
||||
.idea/
|
||||
@@ -3,3 +3,7 @@
|
||||
- Code nach PEP 8, Zeilenlänge maximal 88 Zeichen.
|
||||
- Jede Funktion und Methode hat einen Docstring und Type Hints.
|
||||
- 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_"
|
||||
@@ -0,0 +1,146 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Installiert die Abhängigkeiten aus pyproject.toml in die aktuelle Python-Umgebung.
|
||||
|
||||
Ersatz für "Install requirements" aus PyCharm, wenn das Projekt eine pyproject.toml
|
||||
statt einer requirements.txt hat. Kein Build, keine besondere Projektstruktur nötig,
|
||||
nur Standardbibliothek (Python >= 3.11).
|
||||
|
||||
Benutzung:
|
||||
In PyCharm: Rechtsklick auf diese Datei -> Run 'install_dependencies'
|
||||
Im Terminal (venv aktiv): python install_dependencies.py
|
||||
|
||||
Ohne Parameter wird ALLES installiert:
|
||||
[project].dependencies + alle [project.optional-dependencies] + alle [dependency-groups]
|
||||
|
||||
Abweichendes Verhalten:
|
||||
python install_dependencies.py --extra dev nur Basis + Extra "dev"
|
||||
python install_dependencies.py --group test nur Basis + Gruppe "test"
|
||||
python install_dependencies.py --no-main --group dev
|
||||
python install_dependencies.py --list nur anzeigen, nichts installieren
|
||||
python install_dependencies.py --write requirements.txt schreiben statt installieren
|
||||
python install_dependencies.py --write -o reqs.txt
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
|
||||
if sys.version_info < (3, 11):
|
||||
sys.exit("Dieses Skript braucht Python 3.11 oder neuer (tomllib). "
|
||||
f"Aktuell: {sys.version.split()[0]}")
|
||||
|
||||
import argparse
|
||||
import subprocess
|
||||
import tempfile
|
||||
import tomllib
|
||||
from pathlib import Path
|
||||
|
||||
PROJECT_DIR = Path(__file__).resolve().parent
|
||||
|
||||
|
||||
def resolve_group(groups: dict, name: str, seen: set[str] | None = None) -> list[str]:
|
||||
"""Löst eine Dependency-Group inkl. {include-group = "..."} rekursiv auf."""
|
||||
seen = set() if seen is None else seen
|
||||
if name in seen:
|
||||
raise ValueError(f"Zyklische include-group: {name}")
|
||||
if name not in groups:
|
||||
raise KeyError(f"Dependency-Group '{name}' nicht gefunden")
|
||||
seen.add(name)
|
||||
result: list[str] = []
|
||||
for entry in groups[name]:
|
||||
if isinstance(entry, str):
|
||||
result.append(entry)
|
||||
elif isinstance(entry, dict) and "include-group" in entry:
|
||||
result.extend(resolve_group(groups, entry["include-group"], seen))
|
||||
return result
|
||||
|
||||
|
||||
def collect(data: dict, extras: list[str], groups: list[str], no_main: bool) -> list[str]:
|
||||
project = data.get("project", {})
|
||||
optional = project.get("optional-dependencies", {})
|
||||
dep_groups = data.get("dependency-groups", {})
|
||||
deps: list[str] = []
|
||||
|
||||
if not no_main:
|
||||
deps.extend(project.get("dependencies", []))
|
||||
for extra in extras:
|
||||
if extra not in optional:
|
||||
raise KeyError(f"Optional-Dependency '{extra}' nicht gefunden")
|
||||
deps.extend(optional[extra])
|
||||
for group in groups:
|
||||
deps.extend(resolve_group(dep_groups, group))
|
||||
|
||||
# Duplikate entfernen, Reihenfolge behalten
|
||||
return list(dict.fromkeys(d.strip() for d in deps if d.strip()))
|
||||
|
||||
|
||||
def main() -> int:
|
||||
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
p.add_argument("-p", "--pyproject", type=Path, default=PROJECT_DIR / "pyproject.toml",
|
||||
help="Pfad zur pyproject.toml (Standard: neben diesem Skript)")
|
||||
p.add_argument("--extra", action="append", default=None,
|
||||
help="nur diese optional-dependencies (mehrfach möglich)")
|
||||
p.add_argument("--group", action="append", default=None,
|
||||
help="nur diese dependency-groups (mehrfach möglich)")
|
||||
p.add_argument("--no-main", action="store_true", help="[project].dependencies weglassen")
|
||||
p.add_argument("--list", action="store_true", help="Abhängigkeiten nur anzeigen")
|
||||
p.add_argument("--write", action="store_true", help="requirements-Datei schreiben statt installieren")
|
||||
p.add_argument("-o", "--output", type=Path, default=PROJECT_DIR / "requirements.txt",
|
||||
help="Zieldatei für --write")
|
||||
args = p.parse_args()
|
||||
|
||||
if not args.pyproject.exists():
|
||||
print(f"{args.pyproject} nicht gefunden", file=sys.stderr)
|
||||
return 1
|
||||
data = tomllib.loads(args.pyproject.read_text(encoding="utf-8"))
|
||||
all_extras = list(data.get("project", {}).get("optional-dependencies", {}))
|
||||
all_groups = list(data.get("dependency-groups", {}))
|
||||
|
||||
# Ohne --extra/--group: alles. Mit einem davon: nur das Gewählte.
|
||||
selective = args.extra is not None or args.group is not None
|
||||
extras = (args.extra or []) if selective else all_extras
|
||||
groups = (args.group or []) if selective else all_groups
|
||||
|
||||
try:
|
||||
deps = collect(data, extras, groups, args.no_main)
|
||||
except (KeyError, ValueError) as e:
|
||||
print(f"Fehler: {e.args[0]}", file=sys.stderr)
|
||||
print(f" Vorhandene --extra: {', '.join(all_extras) or '(keine)'}", file=sys.stderr)
|
||||
print(f" Vorhandene --group: {', '.join(all_groups) or '(keine)'}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
parts = ([] if args.no_main else ["Basis"]) + [f"extra:{e}" for e in extras] + [f"group:{g}" for g in groups]
|
||||
print(f"Auswahl: {', '.join(parts) or '(nichts)'}")
|
||||
|
||||
if args.list:
|
||||
print("\n".join(deps) or "(keine Abhängigkeiten)")
|
||||
return 0
|
||||
|
||||
content = f"# Automatisch erzeugt aus {args.pyproject.name} – nicht von Hand bearbeiten\n" + "\n".join(deps) + "\n"
|
||||
|
||||
if args.write:
|
||||
args.output.write_text(content, encoding="utf-8")
|
||||
print(f"{len(deps)} Abhängigkeiten -> {args.output}")
|
||||
return 0
|
||||
|
||||
if not deps:
|
||||
print("Keine Abhängigkeiten gefunden – nichts zu tun.")
|
||||
return 0
|
||||
|
||||
if sys.prefix == sys.base_prefix:
|
||||
print("WARNUNG: Es ist kein virtuelles Environment aktiv – es wird in die globale "
|
||||
f"Python-Installation installiert:\n {sys.prefix}", file=sys.stderr)
|
||||
if sys.stdin.isatty() and input("Trotzdem fortfahren? [j/N] ").strip().lower() not in ("j", "ja", "y", "yes"):
|
||||
return 1
|
||||
|
||||
with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False, encoding="utf-8") as tmp:
|
||||
tmp.write(content)
|
||||
tmp_path = Path(tmp.name)
|
||||
try:
|
||||
print(f"Installiere {len(deps)} Abhängigkeiten in {sys.prefix}\n")
|
||||
return subprocess.call([sys.executable, "-m", "pip", "install", "-r", str(tmp_path)])
|
||||
finally:
|
||||
tmp_path.unlink(missing_ok=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -2,3 +2,9 @@
|
||||
name = "matrixmania"
|
||||
version = "0.1.0"
|
||||
dependencies = ["tabulate", "ruff"]
|
||||
|
||||
[project.optional-dependencies]
|
||||
dev = ["pytest", "ruff", "pytest-cov"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
pythonpath = "src"
|
||||
@@ -0,0 +1,19 @@
|
||||
"""MatrixMania: Matrixberechnungen für Rotation und Projektion."""
|
||||
|
||||
from .compute import (
|
||||
matmul,
|
||||
project_ortho,
|
||||
project_perspective,
|
||||
rot_2D,
|
||||
rot_3D,
|
||||
transpose,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"matmul",
|
||||
"project_ortho",
|
||||
"project_perspective",
|
||||
"rot_2D",
|
||||
"rot_3D",
|
||||
"transpose",
|
||||
]
|
||||
@@ -1,9 +1,7 @@
|
||||
"""Matrix-Funktionen: Multiplikation, Transponieren und 2D-Rotation."""
|
||||
"""Matrix-Funktionen: Multiplikation, Transponieren, Rotation und Projektion."""
|
||||
|
||||
import math
|
||||
|
||||
from tabulate import tabulate
|
||||
|
||||
# Alle Matrizen sind Listen von Zeilen, z.B. [[1, 2], [3, 4]].
|
||||
|
||||
|
||||
@@ -87,6 +85,108 @@ def rot_2D(angle: float) -> list[list[float]]:
|
||||
return [[cos, -sin], [sin, cos]]
|
||||
|
||||
|
||||
def rot_3D(angle: float, axis: str) -> list[list[float]]:
|
||||
"""Gibt die 3D-Rotationsmatrix für eine Drehung um eine Achse zurück.
|
||||
|
||||
Mit c = cos(angle) und s = sin(angle) gilt:
|
||||
|
||||
- Achse "x": [[1, 0, 0], [0, c, -s], [0, s, c]]
|
||||
- Achse "y": [[c, 0, s], [0, 1, 0], [-s, 0, c]]
|
||||
- Achse "z": [[c, -s, 0], [s, c, 0], [0, 0, 1]]
|
||||
|
||||
Parameters
|
||||
----------
|
||||
angle : float
|
||||
Drehwinkel im Bogenmaß.
|
||||
axis : str
|
||||
Drehachse: "x", "y" oder "z".
|
||||
|
||||
Returns
|
||||
-------
|
||||
list[list[float]]
|
||||
Die 3x3-Rotationsmatrix.
|
||||
|
||||
Raises
|
||||
------
|
||||
ValueError
|
||||
Wenn axis nicht "x", "y" oder "z" ist.
|
||||
"""
|
||||
c = math.cos(angle)
|
||||
s = math.sin(angle)
|
||||
if axis == "x":
|
||||
return [[1, 0, 0], [0, c, -s], [0, s, c]]
|
||||
if axis == "y":
|
||||
return [[c, 0, s], [0, 1, 0], [-s, 0, c]]
|
||||
if axis == "z":
|
||||
return [[c, -s, 0], [s, c, 0], [0, 0, 1]]
|
||||
raise ValueError(f"Ungültige Achse {axis!r}, erlaubt sind 'x', 'y' und 'z'")
|
||||
|
||||
|
||||
def project_ortho(
|
||||
point: tuple[float, float, float], scale: float = 1
|
||||
) -> tuple[float, float]:
|
||||
"""Projiziert einen 3D-Punkt orthogonal auf die x-y-Ebene.
|
||||
|
||||
Die z-Koordinate wird ignoriert, x und y werden mit scale multipliziert.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
point : tuple[float, float, float]
|
||||
Der 3D-Punkt (x, y, z).
|
||||
scale : float
|
||||
Skalierungsfaktor für das Ergebnis.
|
||||
|
||||
Returns
|
||||
-------
|
||||
tuple[float, float]
|
||||
Der projizierte 2D-Punkt (x * scale, y * scale).
|
||||
"""
|
||||
x, y, _z = 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 Bildebene.
|
||||
|
||||
Weiter entfernte Punkte (größeres z) erscheinen näher am Ursprung:
|
||||
|
||||
x' = x * focal_length / (z + camera_distance) * scale
|
||||
y' = y * focal_length / (z + camera_distance) * scale
|
||||
|
||||
Parameters
|
||||
----------
|
||||
point : tuple[float, float, float]
|
||||
Der 3D-Punkt (x, y, z).
|
||||
focal_length : float
|
||||
Brennweite: wie stark die Perspektive wirkt.
|
||||
scale : float
|
||||
Skalierungsfaktor für das Ergebnis.
|
||||
camera_distance : float
|
||||
Abstand der Kamera, wird zur z-Koordinate addiert.
|
||||
|
||||
Returns
|
||||
-------
|
||||
tuple[float, float]
|
||||
Der projizierte 2D-Punkt (x', y').
|
||||
|
||||
Raises
|
||||
------
|
||||
ValueError
|
||||
Wenn z + camera_distance gleich 0 ist (Punkt liegt in der Kamera).
|
||||
"""
|
||||
x, y, z = point
|
||||
depth = z + camera_distance
|
||||
if depth == 0:
|
||||
raise ValueError("z + camera_distance darf nicht 0 sein")
|
||||
factor = focal_length / depth * scale
|
||||
return (x * factor, y * factor)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# matmul
|
||||
assert matmul([[1, 2], [3, 4]], [[5, 6], [7, 8]]) == [[19, 22], [43, 50]]
|
||||
@@ -123,4 +223,6 @@ if __name__ == "__main__":
|
||||
print("All tests passed")
|
||||
|
||||
# Rotationsmatrix für 1 rad als Tabelle ausgeben
|
||||
from tabulate import tabulate
|
||||
|
||||
print(tabulate(rot_2D(1.0)))
|
||||
Whitespace-only changes.
@@ -0,0 +1,78 @@
|
||||
"""Tests für project_ortho und project_perspective."""
|
||||
|
||||
import pytest
|
||||
|
||||
from matrixmania import project_ortho, project_perspective
|
||||
|
||||
|
||||
def test_project_ortho_without_scale() -> None:
|
||||
"""Ohne Skalierung wird nur die z-Koordinate weggelassen."""
|
||||
# Arrange
|
||||
point = (1.0, 2.0, 3.0)
|
||||
|
||||
# Act
|
||||
result = project_ortho(point)
|
||||
|
||||
# Assert
|
||||
assert result == (1.0, 2.0)
|
||||
|
||||
|
||||
def test_project_ortho_with_scale_100() -> None:
|
||||
"""Mit scale=100 werden x und y verhundertfacht."""
|
||||
# Arrange
|
||||
point = (1.0, 2.0, 3.0)
|
||||
|
||||
# Act
|
||||
result = project_ortho(point, scale=100)
|
||||
|
||||
# Assert
|
||||
assert result == (100.0, 200.0)
|
||||
|
||||
|
||||
def test_project_perspective_without_scale() -> None:
|
||||
"""Punkt (1, 2, 3), focal_length=1, scale=1: Teilen durch 3 + 4 = 7."""
|
||||
# Arrange
|
||||
point = (1.0, 2.0, 3.0)
|
||||
|
||||
# Act
|
||||
result = project_perspective(point, focal_length=1, scale=1)
|
||||
|
||||
# Assert
|
||||
assert result == pytest.approx((1 / 7, 2 / 7))
|
||||
|
||||
|
||||
def test_project_perspective_with_scale_and_focal_length() -> None:
|
||||
"""Punkt (1, 2, 3), focal_length=2, scale=100: Faktor 2 / 7 * 100."""
|
||||
# Arrange
|
||||
point = (1.0, 2.0, 3.0)
|
||||
|
||||
# Act
|
||||
result = project_perspective(point, focal_length=2, scale=100)
|
||||
|
||||
# Assert
|
||||
assert result == pytest.approx((200 / 7, 400 / 7))
|
||||
|
||||
|
||||
def test_project_perspective_far_point_appears_smaller() -> None:
|
||||
"""Ein weiter entfernter Punkt landet näher am Ursprung."""
|
||||
# Arrange
|
||||
near_point = (1.0, 1.0, 0.0)
|
||||
far_point = (1.0, 1.0, 10.0)
|
||||
|
||||
# Act
|
||||
near = project_perspective(near_point)
|
||||
far = project_perspective(far_point)
|
||||
|
||||
# Assert
|
||||
assert abs(far[0]) < abs(near[0])
|
||||
assert abs(far[1]) < abs(near[1])
|
||||
|
||||
|
||||
def test_project_perspective_point_in_camera_raises_value_error() -> None:
|
||||
"""Liegt der Punkt genau in der Kamera (Tiefe 0), kommt ein ValueError."""
|
||||
# Arrange
|
||||
point = (1.0, 1.0, -4.0)
|
||||
|
||||
# Act / Assert
|
||||
with pytest.raises(ValueError):
|
||||
project_perspective(point, camera_distance=4.0)
|
||||
@@ -0,0 +1,91 @@
|
||||
"""Tests für rot_2D und rot_3D."""
|
||||
|
||||
import math
|
||||
|
||||
import pytest
|
||||
|
||||
from matrixmania import matmul, rot_2D, rot_3D
|
||||
|
||||
|
||||
def test_rot_2D_zero_angle_is_identity() -> None:
|
||||
"""Bei 0 Grad ist die Rotationsmatrix die Einheitsmatrix."""
|
||||
# Arrange
|
||||
angle = 0.0
|
||||
|
||||
# Act
|
||||
result = rot_2D(angle)
|
||||
|
||||
# Assert
|
||||
assert result == [[1, 0], [0, 1]]
|
||||
|
||||
|
||||
def test_rot_2D_quarter_turn_moves_x_axis_to_y_axis() -> None:
|
||||
"""Eine Drehung um 90 Grad bringt (1, 0) nach (0, 1)."""
|
||||
# Arrange
|
||||
point = [[1], [0]]
|
||||
|
||||
# Act
|
||||
rotated = matmul(rot_2D(math.pi / 2), point)
|
||||
|
||||
# Assert
|
||||
assert rotated[0][0] == pytest.approx(0, abs=1e-9)
|
||||
assert rotated[1][0] == pytest.approx(1)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("axis", ["x", "y", "z"])
|
||||
def test_rot_3D_zero_angle_is_identity(axis: str) -> None:
|
||||
"""Bei 0 Grad ist die Rotationsmatrix für jede Achse die Einheitsmatrix."""
|
||||
# Arrange
|
||||
identity = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
|
||||
|
||||
# Act
|
||||
result = rot_3D(0.0, axis)
|
||||
|
||||
# Assert
|
||||
assert result == identity
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("axis", "point", "expected"),
|
||||
[
|
||||
("x", [[0], [1], [0]], [[0], [0], [1]]), # y-Achse -> z-Achse
|
||||
("y", [[0], [0], [1]], [[1], [0], [0]]), # z-Achse -> x-Achse
|
||||
("z", [[1], [0], [0]], [[0], [1], [0]]), # x-Achse -> y-Achse
|
||||
],
|
||||
)
|
||||
def test_rot_3D_quarter_turn(
|
||||
axis: str, point: list[list[float]], expected: list[list[float]]
|
||||
) -> None:
|
||||
"""Eine Drehung um 90 Grad dreht die Achsen wie erwartet weiter."""
|
||||
# Arrange
|
||||
rotation = rot_3D(math.pi / 2, axis)
|
||||
|
||||
# Act
|
||||
result = matmul(rotation, point)
|
||||
|
||||
# Assert
|
||||
for row, expected_row in zip(result, expected, strict=True):
|
||||
assert row[0] == pytest.approx(expected_row[0], abs=1e-9)
|
||||
|
||||
|
||||
def test_rot_3D_point_on_axis_stays_unchanged() -> None:
|
||||
"""Ein Punkt auf der Drehachse bleibt bei der Drehung liegen."""
|
||||
# Arrange
|
||||
point_on_x_axis = [[2], [0], [0]]
|
||||
|
||||
# Act
|
||||
result = matmul(rot_3D(1.2, "x"), point_on_x_axis)
|
||||
|
||||
# Assert
|
||||
assert result == [[2], [0], [0]]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("axis", ["a", "X", "", "xy"])
|
||||
def test_rot_3D_invalid_axis_raises_value_error(axis: str) -> None:
|
||||
"""Ungültige Achsen führen zu einem ValueError."""
|
||||
# Arrange
|
||||
angle = 1.0
|
||||
|
||||
# Act / Assert
|
||||
with pytest.raises(ValueError):
|
||||
rot_3D(angle, axis)
|
||||
Reference in new issue
Block a user