Compare commits
4
Commits
7909016431
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3c3891d892 | ||
|
|
a2c98da4d2 | ||
|
|
5b72de9e05 | ||
|
|
96dce24e8b |
No files matched your search
@@ -2,4 +2,6 @@
|
||||
|
||||
- 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`
|
||||
- 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())
|
||||
+8
-1
@@ -1,4 +1,11 @@
|
||||
[project]
|
||||
name = "matrixmania"
|
||||
version = "0.1.0"
|
||||
dependencies = ["tabulate", "ruff"]
|
||||
dependencies = ["tabulate", "ruff"]
|
||||
|
||||
[project.optional-dependencies]
|
||||
dev = ["pytest", "ruff", "pytest-cov"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
pythonpath = ["src"]
|
||||
testpaths = ["test"]
|
||||
@@ -0,0 +1,3 @@
|
||||
from .compute import matmul, transpose, rot_2D, rot_3D, project_perspective
|
||||
# Damit project_ortho direkt aus matrixmania importiert werden kann.
|
||||
from .compute import project_ortho
|
||||
@@ -1,3 +1,12 @@
|
||||
#Katzenaufgabe: 1. funktionierender Stand war committed.
|
||||
#2. in compute.py und pyproject.toml absichtlich Änderungen/Quatsch gemacht.
|
||||
#3. Diese Änderungen nicht committed.
|
||||
#4. ↩ Git → Uncommitted Changes → Rollback ausgeführt.
|
||||
#5. Danach waren die Katzen-Änderungen wieder verschwunden und die Dateien wieder wie vorher.
|
||||
|
||||
#Dann: Katze erledigt.
|
||||
|
||||
|
||||
# Matrixfunktionen für das Projekt MatrixMania
|
||||
|
||||
#Was die Aufgabe war:
|
||||
@@ -20,6 +29,7 @@
|
||||
|
||||
"""Matrix-Operationen ohne externe Bibliotheken (reine Python-Listen)."""
|
||||
import math
|
||||
from math import cos, sin
|
||||
|
||||
from tabulate import tabulate
|
||||
|
||||
@@ -117,6 +127,108 @@ def rot_2D(theta: float) -> Matrix:
|
||||
return [[cosine, -sine], [sine, cosine]]
|
||||
|
||||
|
||||
def rot_3D(angle: float, axis: str) -> list[list[float]]:
|
||||
"""Erzeugt eine Rotationsmatrix für eine Drehung im 3D-Raum.
|
||||
|
||||
Args:
|
||||
angle: Drehwinkel im Bogenmaß.
|
||||
axis: Drehachse "x", "y" oder "z".
|
||||
|
||||
Returns:
|
||||
Die zur Achse passende 3x3-Rotationsmatrix.
|
||||
|
||||
Raises:
|
||||
ValueError: Wenn axis weder "x", "y" noch "z" ist.
|
||||
|
||||
Formeln mit c = cos(angle) und s = sin(angle):
|
||||
|
||||
Rotation um die x-Achse:
|
||||
[1, 0, 0]
|
||||
[0, c, -s]
|
||||
[0, s, c]
|
||||
|
||||
Rotation um die y-Achse:
|
||||
[ c, 0, s]
|
||||
[ 0, 1, 0]
|
||||
[-s, 0, c]
|
||||
|
||||
Rotation um die z-Achse:
|
||||
[c, -s, 0]
|
||||
[s, c, 0]
|
||||
[0, 0, 1]
|
||||
"""
|
||||
c = cos(angle)
|
||||
s = sin(angle)
|
||||
|
||||
if axis == "x":
|
||||
return [
|
||||
[1.0, 0.0, 0.0],
|
||||
[0.0, c, -s],
|
||||
[0.0, s, c],
|
||||
]
|
||||
|
||||
if axis == "y":
|
||||
return [
|
||||
[c, 0.0, s],
|
||||
[0.0, 1.0, 0.0],
|
||||
[-s, 0.0, c],
|
||||
]
|
||||
|
||||
if axis == "z":
|
||||
return [
|
||||
[c, -s, 0.0],
|
||||
[s, c, 0.0],
|
||||
[0.0, 0.0, 1.0],
|
||||
]
|
||||
|
||||
raise ValueError("axis muss 'x', 'y' oder 'z' sein.")
|
||||
|
||||
|
||||
def project_ortho(
|
||||
point: tuple[float, float, float],
|
||||
scale: float = 1,
|
||||
) -> tuple[float, float]:
|
||||
"""Projiziert einen 3D-Punkt auf die xy-Ebene und skaliert ihn."""
|
||||
|
||||
# Die ersten beiden Koordinaten des Punktes auslesen.
|
||||
# Python beginnt beim Zählen mit 0.
|
||||
x = point[0]
|
||||
y = point[1]
|
||||
|
||||
# Die dritte Koordinate point[2] ist z.
|
||||
# Für diese Projektion brauchen wir sie nicht.
|
||||
|
||||
# x und y skalieren und als Tupel zurückgeben.
|
||||
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 eine 2D-Ebene."""
|
||||
|
||||
# Wir verteilen die drei Koordinaten auf einzelne Variablen.
|
||||
x, y, z = point
|
||||
|
||||
# Die Tiefe des Punktes wird um den Kameraabstand verschoben.
|
||||
depth = z + camera_distance
|
||||
|
||||
# Durch 0 darf nicht geteilt werden.
|
||||
# Ein Punkt auf der Kameraebene kann so nicht projiziert werden.
|
||||
if depth == 0:
|
||||
raise ValueError(
|
||||
"Der Punkt darf nicht auf der Kameraebene liegen."
|
||||
)
|
||||
|
||||
# Wir berechnen die horizontalen und vertikalen Bildschirmkoordinaten.
|
||||
projected_x = x * focal_length / depth * scale
|
||||
projected_y = y * focal_length / depth * scale
|
||||
|
||||
# Aus dem 3D-Punkt wird ein 2D-Punkt.
|
||||
return projected_x, projected_y
|
||||
|
||||
if __name__ == "__main__": #führe den testcode nur aus wenn compute.py direkt gestartet wird
|
||||
matrix_a = [
|
||||
[3, 4, -1, 4],
|
||||
Whitespace-only changes.
@@ -0,0 +1,88 @@
|
||||
# pytest hilft uns beim Testen und Vergleichen von Kommazahlen.
|
||||
import pytest
|
||||
|
||||
# Wir importieren die Funktionen, die wir testen möchten.
|
||||
from matrixmania import project_ortho, project_perspective
|
||||
|
||||
|
||||
def test_project_ortho_without_scaling():
|
||||
"""Prüft die orthogonale Projektion mit Standardwerten."""
|
||||
|
||||
# Arrange: Einen 3D-Punkt vorbereiten.
|
||||
point = (1.0, 2.0, 3.0)
|
||||
|
||||
# Act: Ohne zusätzliche Skalierung projizieren.
|
||||
result = project_ortho(point)
|
||||
|
||||
# Assert: x und y bleiben gleich, z fällt weg.
|
||||
assert result == (1.0, 2.0)
|
||||
|
||||
|
||||
def test_project_ortho_with_scaling():
|
||||
"""Prüft die orthogonale Projektion mit Skalierung 100."""
|
||||
|
||||
# Arrange: Einen 3D-Punkt vorbereiten.
|
||||
point = (1.0, 2.0, 3.0)
|
||||
|
||||
# Act: Mit Skalierungsfaktor 100 projizieren.
|
||||
result = project_ortho(point, scale=100)
|
||||
|
||||
# Assert: x und y werden jeweils mit 100 multipliziert.
|
||||
assert result == (100.0, 200.0)
|
||||
|
||||
|
||||
def test_project_perspective_without_scaling():
|
||||
"""Prüft die perspektivische Projektion mit Standardwerten."""
|
||||
|
||||
# Arrange: Einen 3D-Punkt vorbereiten.
|
||||
point = (1.0, 2.0, 3.0)
|
||||
|
||||
# Act: Die Standardwerte der Funktion verwenden.
|
||||
result = project_perspective(point)
|
||||
|
||||
# Assert: Die Tiefe ist z + camera_distance = 3 + 4 = 7.
|
||||
# Deshalb erwarten wir x = 1/7 und y = 2/7.
|
||||
assert result == pytest.approx((1 / 7, 2 / 7))
|
||||
|
||||
|
||||
def test_project_perspective_with_focal_length_and_scaling():
|
||||
"""Prüft die Projektion mit Brennweite 2 und Skalierung 100."""
|
||||
|
||||
# Arrange: Einen 3D-Punkt vorbereiten.
|
||||
point = (1.0, 2.0, 3.0)
|
||||
|
||||
# Act: Brennweite 2 und Skalierungsfaktor 100 verwenden.
|
||||
result = project_perspective(point, focal_length=2, scale=100)
|
||||
|
||||
# Assert: Die Tiefe ist weiterhin 7.
|
||||
# x = 1 * 2 / 7 * 100 = 200/7.
|
||||
# y = 2 * 2 / 7 * 100 = 400/7.
|
||||
assert result == pytest.approx((200 / 7, 400 / 7))
|
||||
|
||||
|
||||
def test_project_perspective_with_custom_camera_distance():
|
||||
"""Prüft die Projektion mit einem anderen Kameraabstand."""
|
||||
|
||||
# Arrange: Punkt und erwartetes Ergebnis vorbereiten.
|
||||
# Die Tiefe ist z + camera_distance = 3 + 1 = 4.
|
||||
point = (1.0, 2.0, 3.0)
|
||||
expected = (0.25, 0.5)
|
||||
|
||||
# Act: Den Kameraabstand auf 1 setzen.
|
||||
result = project_perspective(point, camera_distance=1.0)
|
||||
|
||||
# Assert: x = 1/4 und y = 2/4.
|
||||
assert result == pytest.approx(expected)
|
||||
|
||||
|
||||
def test_project_perspective_with_zero_scale():
|
||||
"""Prüft die Projektion mit Skalierungsfaktor 0."""
|
||||
|
||||
# Arrange: Einen gültigen 3D-Punkt vorbereiten.
|
||||
point = (1.0, 2.0, 3.0)
|
||||
|
||||
# Act: Den Skalierungsfaktor auf 0 setzen.
|
||||
result = project_perspective(point, scale=0.0)
|
||||
|
||||
# Assert: Beide Koordinaten werden mit 0 multipliziert.
|
||||
assert result == pytest.approx((0.0, 0.0))
|
||||
@@ -0,0 +1,96 @@
|
||||
from math import pi
|
||||
|
||||
import pytest
|
||||
|
||||
from matrixmania import rot_2D, rot_3D
|
||||
|
||||
|
||||
def test_rot_2D_90_degrees():
|
||||
# Arrange
|
||||
angle = pi / 2
|
||||
expected = [
|
||||
[0.0, -1.0],
|
||||
[1.0, 0.0],
|
||||
]
|
||||
|
||||
# Act
|
||||
result = rot_2D(angle)
|
||||
|
||||
# Assert
|
||||
assert len(result) == len(expected)
|
||||
for actual_row, expected_row in zip(result, expected):
|
||||
assert actual_row == pytest.approx(expected_row)
|
||||
|
||||
|
||||
def test_rot_2D_invalid_angle():
|
||||
# Arrange
|
||||
angle = "ungueltig"
|
||||
|
||||
# Act & Assert:
|
||||
# Aufruf ausführen und prüfen, dass ein TypeError entsteht.
|
||||
with pytest.raises(TypeError):
|
||||
rot_2D(angle)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"axis, expected",
|
||||
[
|
||||
(
|
||||
"x",
|
||||
[
|
||||
[1.0, 0.0, 0.0],
|
||||
[0.0, 0.0, -1.0],
|
||||
[0.0, 1.0, 0.0],
|
||||
],
|
||||
),
|
||||
(
|
||||
"y",
|
||||
[
|
||||
[0.0, 0.0, 1.0],
|
||||
[0.0, 1.0, 0.0],
|
||||
[-1.0, 0.0, 0.0],
|
||||
],
|
||||
),
|
||||
(
|
||||
"z",
|
||||
[
|
||||
[0.0, -1.0, 0.0],
|
||||
[1.0, 0.0, 0.0],
|
||||
[0.0, 0.0, 1.0],
|
||||
],
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_rot_3D_90_degrees(axis, expected):
|
||||
# Arrange
|
||||
angle = pi / 2
|
||||
|
||||
# Act
|
||||
result = rot_3D(angle, axis)
|
||||
|
||||
# Assert
|
||||
assert len(result) == len(expected)
|
||||
for actual_row, expected_row in zip(result, expected):
|
||||
assert actual_row == pytest.approx(expected_row)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("axis", ["a", "", "X"])
|
||||
def test_rot_3D_invalid_axis(axis):
|
||||
# Arrange
|
||||
angle = pi / 2
|
||||
|
||||
# Act & Assert:
|
||||
# Aufruf ausführen und den erwarteten ValueError prüfen.
|
||||
with pytest.raises(ValueError):
|
||||
rot_3D(angle, axis)
|
||||
|
||||
|
||||
def test_rot_3D_invalid_angle():
|
||||
# Arrange
|
||||
angle = "ungueltig"
|
||||
axis = "x"
|
||||
|
||||
# Act & Assert:
|
||||
# Aufruf ausführen und den erwarteten TypeError prüfen.
|
||||
with pytest.raises(TypeError):
|
||||
rot_3D(angle, axis)
|
||||
Reference in new issue
Block a user