Addd pytest and rot_3d in compute
This commit is contained in:
1 parent
cb85e8b86c
commit
56755169a6
9 files changed
+316
-3
No files matched your search
@@ -2,3 +2,7 @@
|
|||||||
- 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_"
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import pygame
|
import pygame
|
||||||
|
|
||||||
from compute import rot_2d
|
from src.matrixmania.compute import rot_2d
|
||||||
from moon import MOON_RADIUS, Moon, Point
|
from moon import MOON_RADIUS, Moon, Point
|
||||||
|
|
||||||
APOLLO_RADIUS = 4
|
APOLLO_RADIUS = 4
|
||||||
|
|||||||
@@ -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,7 +2,7 @@
|
|||||||
|
|
||||||
import pygame
|
import pygame
|
||||||
|
|
||||||
from compute import matmul, rot_2d, transpose
|
from src.matrixmania.compute import matmul, rot_2d, transpose
|
||||||
from game import Game
|
from game import Game
|
||||||
|
|
||||||
EARTH_RADIUS = 30
|
EARTH_RADIUS = 30
|
||||||
|
|||||||
@@ -2,3 +2,11 @@
|
|||||||
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"
|
||||||
|
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
from .compute import matmul, rot_2d, rot_3D, transpose
|
||||||
|
|
||||||
|
__all__ = ["matmul", "rot_2d", "rot_3D", "transpose"]
|
||||||
@@ -8,7 +8,7 @@ from typing import Literal
|
|||||||
|
|
||||||
from tabulate import tabulate
|
from tabulate import tabulate
|
||||||
|
|
||||||
__all__ = ["matmul", "print_matrix", "rot_2d", "rotate", "transpose"]
|
__all__ = ["matmul", "print_matrix", "rot_2d", "rot_3D", "rotate", "transpose"]
|
||||||
|
|
||||||
_NUMERIC_TYPES = (int, float)
|
_NUMERIC_TYPES = (int, float)
|
||||||
|
|
||||||
@@ -162,6 +162,66 @@ def rot_2d(angle: float, unit: Literal["deg", "rad"] = "deg") -> list[list[float
|
|||||||
return [[c, -s], [s, c]]
|
return [[c, -s], [s, c]]
|
||||||
|
|
||||||
|
|
||||||
|
def rot_3D(
|
||||||
|
angle: float, axis: str, unit: Literal["deg", "rad"] = "deg"
|
||||||
|
) -> list[list[float]]:
|
||||||
|
"""Return a 3×3 rotation matrix for a given angle and axis.
|
||||||
|
|
||||||
|
The supported rotation matrices are:
|
||||||
|
|
||||||
|
.. math::
|
||||||
|
|
||||||
|
R_x = \\begin{bmatrix}
|
||||||
|
1 & 0 & 0 \\\\
|
||||||
|
0 & \\cos\\theta & -\\sin\\theta \\\\
|
||||||
|
0 & \\sin\\theta & \\cos\\theta
|
||||||
|
\\end{bmatrix}
|
||||||
|
|
||||||
|
R_y = \\begin{bmatrix}
|
||||||
|
\\cos\\theta & 0 & \\sin\\theta \\\\
|
||||||
|
0 & 1 & 0 \\\\
|
||||||
|
-\\sin\\theta & 0 & \\cos\\theta
|
||||||
|
\\end{bmatrix}
|
||||||
|
|
||||||
|
R_z = \\begin{bmatrix}
|
||||||
|
\\cos\\theta & -\\sin\\theta & 0 \\\\
|
||||||
|
\\sin\\theta & \\cos\\theta & 0 \\\\
|
||||||
|
0 & 0 & 1
|
||||||
|
\\end{bmatrix}
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
angle : float
|
||||||
|
Rotation angle.
|
||||||
|
axis : {"x", "y", "z"}
|
||||||
|
Axis around which to rotate.
|
||||||
|
unit : {"deg", "rad"}, default "deg"
|
||||||
|
Whether *angle* is given in degrees or radians.
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
list[list[float]]
|
||||||
|
3×3 rotation matrix.
|
||||||
|
|
||||||
|
Raises
|
||||||
|
------
|
||||||
|
ValueError
|
||||||
|
If *axis* is not one of ``"x"``, ``"y"`` or ``"z"``.
|
||||||
|
"""
|
||||||
|
if axis not in ("x", "y", "z"):
|
||||||
|
raise ValueError(f"axis must be 'x', 'y' or 'z', got {axis!r}")
|
||||||
|
|
||||||
|
theta = math.radians(angle) if unit == "deg" else angle
|
||||||
|
c = math.cos(theta)
|
||||||
|
s = math.sin(theta)
|
||||||
|
|
||||||
|
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]]
|
||||||
|
return [[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]
|
||||||
|
|
||||||
|
|
||||||
def print_matrix(title: str, matrix: list[list[float]]) -> None:
|
def print_matrix(title: str, matrix: list[list[float]]) -> None:
|
||||||
"""Print a title followed by each matrix row on its own line."""
|
"""Print a title followed by each matrix row on its own line."""
|
||||||
print(title)
|
print(title)
|
||||||
Whitespace-only changes.
@@ -0,0 +1,92 @@
|
|||||||
|
"""Tests for the 2-D and 3-D rotation helpers in :mod:`matrixmania.compute`."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import math
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from matrixmania.compute import rot_2d, rot_3D
|
||||||
|
|
||||||
|
|
||||||
|
def assert_matrix_close(actual: list[list[float]], expected: list[list[float]]) -> None:
|
||||||
|
"""Assert that two matrices are numerically equal element by element."""
|
||||||
|
assert len(actual) == len(expected)
|
||||||
|
for actual_row, expected_row in zip(actual, expected):
|
||||||
|
assert len(actual_row) == len(expected_row)
|
||||||
|
assert actual_row == pytest.approx(expected_row)
|
||||||
|
|
||||||
|
|
||||||
|
class TestRot2D:
|
||||||
|
"""Tests for :func:`matrixmania.compute.rot_2d`."""
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"angle,expected",
|
||||||
|
[
|
||||||
|
(0, [[1.0, 0.0], [0.0, 1.0]]),
|
||||||
|
(90, [[0.0, -1.0], [1.0, 0.0]]),
|
||||||
|
(180, [[-1.0, 0.0], [0.0, -1.0]]),
|
||||||
|
(-90, [[0.0, 1.0], [-1.0, 0.0]]),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_degrees(self, angle: float, expected: list[list[float]]) -> None:
|
||||||
|
"""Rotation matrices for angles given in degrees."""
|
||||||
|
assert_matrix_close(rot_2d(angle), expected)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"angle",
|
||||||
|
[0.0, math.pi / 2, math.pi, -math.pi / 2],
|
||||||
|
)
|
||||||
|
def test_radians(self, angle: float) -> None:
|
||||||
|
"""Radians and equivalent degrees yield the same matrix."""
|
||||||
|
assert_matrix_close(
|
||||||
|
rot_2d(angle, unit="rad"), rot_2d(math.degrees(angle), unit="deg")
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_default_unit_is_degrees(self) -> None:
|
||||||
|
"""The default unit is degrees."""
|
||||||
|
assert_matrix_close(rot_2d(90), rot_2d(math.pi / 2, unit="rad"))
|
||||||
|
|
||||||
|
|
||||||
|
class TestRot3D:
|
||||||
|
"""Tests for :func:`matrixmania.compute.rot_3D`."""
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("axis", ["x", "y", "z"])
|
||||||
|
def test_zero_degrees_is_identity(self, axis: str) -> None:
|
||||||
|
"""A zero rotation yields the identity matrix for every axis."""
|
||||||
|
expected = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
|
||||||
|
assert_matrix_close(rot_3D(0, axis), expected)
|
||||||
|
|
||||||
|
def test_x_90_degrees(self) -> None:
|
||||||
|
"""Rotation of 90 degrees around the x axis."""
|
||||||
|
expected = [[1.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]]
|
||||||
|
assert_matrix_close(rot_3D(90, "x"), expected)
|
||||||
|
|
||||||
|
def test_y_90_degrees(self) -> None:
|
||||||
|
"""Rotation of 90 degrees around the y axis."""
|
||||||
|
expected = [[0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [-1.0, 0.0, 0.0]]
|
||||||
|
assert_matrix_close(rot_3D(90, "y"), expected)
|
||||||
|
|
||||||
|
def test_z_90_degrees(self) -> None:
|
||||||
|
"""Rotation of 90 degrees around the z axis."""
|
||||||
|
expected = [[0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]
|
||||||
|
assert_matrix_close(rot_3D(90, "z"), expected)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("axis", ["x", "y", "z"])
|
||||||
|
def test_radians_match_degrees(self, axis: str) -> None:
|
||||||
|
"""Radians and equivalent degrees yield the same matrix."""
|
||||||
|
angle_rad = math.pi / 2
|
||||||
|
assert_matrix_close(
|
||||||
|
rot_3D(angle_rad, axis, unit="rad"),
|
||||||
|
rot_3D(math.degrees(angle_rad), axis, unit="deg"),
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_default_unit_is_degrees(self) -> None:
|
||||||
|
"""The default unit is degrees."""
|
||||||
|
assert_matrix_close(rot_3D(90, "z"), rot_3D(math.pi / 2, "z", unit="rad"))
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("axis", ["a", "X", "", "xy"])
|
||||||
|
def test_invalid_axis_raises(self, axis: str) -> None:
|
||||||
|
"""An unsupported axis raises ``ValueError``."""
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
rot_3D(90, axis)
|
||||||
Reference in new issue
Block a user