initialer commit
This commit is contained in:
1 parent
74776ef485
commit
a3095c2df9
18 files changed
+1073
No files matched your search
@@ -0,0 +1,10 @@
|
||||
# Regeln für dieses Projekt
|
||||
|
||||
- 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_"
|
||||
- Tests sind nach Arrange, Act, Assert gegliedert
|
||||
@@ -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())
|
||||
@@ -0,0 +1,10 @@
|
||||
[project]
|
||||
name = "matrixmania"
|
||||
version = "0.1.0"
|
||||
dependencies = ["tabulate"]
|
||||
|
||||
[project.optional-dependencies]
|
||||
dev = ["pytest", "ruff", "pytest-cov"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
pythonpath = "src"
|
||||
@@ -0,0 +1,19 @@
|
||||
"""Paket MatrixMania: Matrixfunktionen 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",
|
||||
]
|
||||
@@ -0,0 +1,174 @@
|
||||
"""Funktionen zur linearen Algebra auf Matrizen als verschachtelte Listen."""
|
||||
|
||||
import math
|
||||
|
||||
from tabulate import tabulate
|
||||
|
||||
|
||||
def matmul(
|
||||
matrix_a: list[list[float]], matrix_b: list[list[float]]
|
||||
) -> list[list[float]]:
|
||||
"""
|
||||
Multipliziert zwei Matrizen miteinander (A * B).
|
||||
|
||||
:param matrix_a: Linke Matrix mit m Zeilen und n Spalten
|
||||
:param matrix_b: Rechte Matrix mit n Zeilen und p Spalten
|
||||
:return: Ergebnismatrix mit m Zeilen und p Spalten
|
||||
:raises ValueError: Wenn die Spaltenzahl von A nicht der Zeilenzahl von B entspricht
|
||||
"""
|
||||
if len(matrix_a[0]) != len(matrix_b):
|
||||
raise ValueError("Spaltenzahl von A muss der Zeilenzahl von B entsprechen.")
|
||||
|
||||
result = []
|
||||
for row in matrix_a:
|
||||
new_row = []
|
||||
for col_index in range(len(matrix_b[0])):
|
||||
value = 0
|
||||
for k in range(len(row)):
|
||||
value += row[k] * matrix_b[k][col_index]
|
||||
new_row.append(value)
|
||||
result.append(new_row)
|
||||
return result
|
||||
|
||||
|
||||
def transpose(matrix: list[list[float]]) -> list[list[float]]:
|
||||
"""
|
||||
Transponiert eine Matrix: Zeilen werden zu Spalten und Spalten zu Zeilen.
|
||||
|
||||
:param matrix: Matrix mit m Zeilen und n Spalten
|
||||
:return: Transponierte Matrix mit n Zeilen und m Spalten
|
||||
:raises ValueError: Bei leerer Matrix oder unterschiedlich langen Zeilen
|
||||
"""
|
||||
if not matrix or not matrix[0]:
|
||||
raise ValueError("Die Matrix darf nicht leer sein.")
|
||||
|
||||
column_count = len(matrix[0])
|
||||
for row in matrix:
|
||||
if len(row) != column_count:
|
||||
raise ValueError("Alle Zeilen müssen gleich viele Spalten haben.")
|
||||
|
||||
result = []
|
||||
for col_index in range(column_count):
|
||||
new_row = []
|
||||
for row in matrix:
|
||||
new_row.append(row[col_index])
|
||||
result.append(new_row)
|
||||
return result
|
||||
|
||||
|
||||
def rot_2D(angle: float) -> list[list[float]]:
|
||||
"""
|
||||
Liefert die 2D-Rotationsmatrix für eine Drehung um den Ursprung.
|
||||
|
||||
:param angle: Drehwinkel im Bogenmaß (gegen den Uhrzeigersinn)
|
||||
:return: 2x2-Rotationsmatrix [[cos, -sin], [sin, cos]]
|
||||
"""
|
||||
return [
|
||||
[math.cos(angle), -math.sin(angle)],
|
||||
[math.sin(angle), math.cos(angle)],
|
||||
]
|
||||
|
||||
|
||||
def rot_3D(angle: float, axis: str) -> list[list[float]]:
|
||||
"""
|
||||
Liefert die 3D-Rotationsmatrix für eine Drehung um eine Koordinatenachse.
|
||||
|
||||
Formeln (θ = angle):
|
||||
|
||||
- x-Achse: [[1, 0, 0], [0, cos θ, -sin θ], [0, sin θ, cos θ]]
|
||||
- y-Achse: [[cos θ, 0, sin θ], [0, 1, 0], [-sin θ, 0, cos θ]]
|
||||
- z-Achse: [[cos θ, -sin θ, 0], [sin θ, cos θ, 0], [0, 0, 1]]
|
||||
|
||||
:param angle: Drehwinkel im Bogenmaß
|
||||
:param axis: Drehachse, "x", "y" oder "z"
|
||||
:return: 3x3-Rotationsmatrix
|
||||
:raises ValueError: Wenn axis nicht "x", "y" oder "z" ist
|
||||
"""
|
||||
cos = math.cos(angle)
|
||||
sin = math.sin(angle)
|
||||
if axis == "x":
|
||||
return [[1, 0, 0], [0, cos, -sin], [0, sin, cos]]
|
||||
if axis == "y":
|
||||
return [[cos, 0, sin], [0, 1, 0], [-sin, 0, cos]]
|
||||
if axis == "z":
|
||||
return [[cos, -sin, 0], [sin, cos, 0], [0, 0, 1]]
|
||||
raise ValueError(f"Ungültige Achse '{axis}', 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 xy-Ebene.
|
||||
|
||||
Die z-Koordinate wird ignoriert, x und y werden mit scale multipliziert.
|
||||
|
||||
:param point: 3D-Punkt (x, y, z)
|
||||
:param scale: Skalierungsfaktor für das Ergebnis
|
||||
:return: 2D-Punkt (x * scale, y * scale)
|
||||
"""
|
||||
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.
|
||||
|
||||
Formel: x' = x * focal_length / (z + camera_distance) * scale,
|
||||
y' entsprechend.
|
||||
|
||||
:param point: 3D-Punkt (x, y, z)
|
||||
:param focal_length: Brennweite, steuert die Stärke der Perspektive
|
||||
:param scale: Skalierungsfaktor für das Ergebnis
|
||||
:param camera_distance: Abstand der Kamera zum Ursprung
|
||||
:return: 2D-Punkt (x', y')
|
||||
:raises ValueError: Wenn der Punkt auf Höhe oder hinter der Kamera liegt
|
||||
"""
|
||||
x, y, z = point
|
||||
depth = z + camera_distance
|
||||
if depth <= 0:
|
||||
raise ValueError("Der Punkt liegt auf Höhe oder hinter der Kamera.")
|
||||
factor = focal_length / depth * scale
|
||||
return (x * factor, y * factor)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Test matmul (Beispiel aus dem Skript)
|
||||
matrix_a = [[3, 4, -1, 4], [-2, 2, 5, 1]]
|
||||
matrix_b = [[1, 3, -2], [2, 5, 1], [-1, 4, -4], [2, 3, 6]]
|
||||
matrix_c = matmul(matrix_a, matrix_b)
|
||||
print("Ergebnis C = A * B:")
|
||||
for row in matrix_c:
|
||||
print(row)
|
||||
|
||||
# Zweites Beispiel matmul: Einheitsmatrix ändert nichts
|
||||
identity = [[1, 0], [0, 1]]
|
||||
print("\nEinheitsmatrix * [[5, 6], [7, 8]]:")
|
||||
print(matmul(identity, [[5, 6], [7, 8]])) # Erwartet: [[5, 6], [7, 8]]
|
||||
|
||||
# Fehlerfall matmul: Dimensionen passen nicht
|
||||
try:
|
||||
matmul([[1, 2]], [[1, 2]])
|
||||
except ValueError as error:
|
||||
print("ValueError wie erwartet:", error)
|
||||
|
||||
# Test transpose
|
||||
matrix = [[1, 2, 3], [4, 5, 6]]
|
||||
print("\nTransponiert:")
|
||||
print(transpose(matrix)) # Erwartet: [[1, 4], [2, 5], [3, 6]]
|
||||
|
||||
# Test rot_2D: Punkt (1, 0) um 90 Grad drehen -> erwartet (0, 1)
|
||||
point = transpose([[1, 0]]) # [x, y] wird zur Spalte [[x], [y]]
|
||||
rotated = matmul(rot_2D(math.pi / 2), point)
|
||||
print("\nPunkt (1, 0) um 90 Grad gedreht:")
|
||||
print(round(rotated[0][0], 10), round(rotated[1][0], 10)) # Erwartet: 0.0 1.0
|
||||
|
||||
# Requirements: Matrix mit tabulate ausgeben
|
||||
print("\nRotationsmatrix für 1.0 als Tabelle:")
|
||||
print(tabulate(rot_2D(1.0)))
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Tests für project_ortho und project_perspective."""
|
||||
|
||||
import pytest
|
||||
|
||||
from matrixmania import project_ortho, project_perspective
|
||||
|
||||
|
||||
def test_project_ortho_without_scale():
|
||||
# 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():
|
||||
# Arrange
|
||||
point = (1.0, 2.0, 3.0)
|
||||
# Act
|
||||
result = project_ortho(point, scale=100)
|
||||
# Assert
|
||||
assert result == pytest.approx((100.0, 200.0))
|
||||
|
||||
|
||||
def test_project_perspective_without_scale():
|
||||
# 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_100_and_focal_length_2():
|
||||
# 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():
|
||||
# Arrange
|
||||
near = (1.0, 1.0, 0.0)
|
||||
far = (1.0, 1.0, 10.0)
|
||||
# Act
|
||||
near_x, _ = project_perspective(near)
|
||||
far_x, _ = project_perspective(far)
|
||||
# Assert
|
||||
assert far_x < near_x
|
||||
|
||||
|
||||
def test_project_perspective_point_behind_camera_raises():
|
||||
# Arrange
|
||||
point = (1.0, 1.0, -4.0)
|
||||
# Act & Assert
|
||||
with pytest.raises(ValueError):
|
||||
project_perspective(point)
|
||||
@@ -0,0 +1,65 @@
|
||||
"""Tests für rot_2D und rot_3D."""
|
||||
|
||||
import math
|
||||
|
||||
import pytest
|
||||
|
||||
from matrixmania import matmul, rot_2D, rot_3D, transpose
|
||||
|
||||
|
||||
def rotate(matrix: list[list[float]], point: list[float]) -> list[float]:
|
||||
"""Dreht einen Punkt mit einer Rotationsmatrix und gibt ihn als Liste zurück."""
|
||||
result = matmul(matrix, transpose([point]))
|
||||
return [row[0] for row in result]
|
||||
|
||||
|
||||
def test_rot_2D_90_degrees():
|
||||
# Arrange
|
||||
point = [1, 0]
|
||||
# Act
|
||||
rotated = rotate(rot_2D(math.pi / 2), point)
|
||||
# Assert
|
||||
assert rotated == pytest.approx([0, 1])
|
||||
|
||||
|
||||
def test_rot_2D_zero_angle_is_identity():
|
||||
# Arrange
|
||||
angle = 0
|
||||
# Act
|
||||
matrix = rot_2D(angle)
|
||||
# Assert
|
||||
assert matrix == [[1, 0], [0, 1]]
|
||||
|
||||
|
||||
@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_90_degrees(axis, point, expected):
|
||||
# Arrange
|
||||
angle = math.pi / 2
|
||||
# Act
|
||||
rotated = rotate(rot_3D(angle, axis), point)
|
||||
# Assert
|
||||
assert rotated == pytest.approx(expected)
|
||||
|
||||
|
||||
def test_rot_3D_point_on_axis_stays():
|
||||
# Arrange
|
||||
point = [1, 0, 0]
|
||||
# Act
|
||||
rotated = rotate(rot_3D(1.23, "x"), point)
|
||||
# Assert
|
||||
assert rotated == pytest.approx(point)
|
||||
|
||||
|
||||
def test_rot_3D_invalid_axis_raises():
|
||||
# Arrange
|
||||
axis = "w"
|
||||
# Act & Assert
|
||||
with pytest.raises(ValueError):
|
||||
rot_3D(1.0, axis)
|
||||
Reference in new issue
Block a user