Tests für rot_2D und rot_3D
This commit is contained in:
1 parent
70e1a351f3
commit
7753115638
6 files changed
+196
-54
No files matched your search
+53
-16
@@ -1,5 +1,3 @@
|
||||
|
||||
|
||||
"""Utility functions for matrix operations.
|
||||
|
||||
This module contains:
|
||||
@@ -38,6 +36,7 @@ def matmul(a: Matrix, b: Matrix) -> Matrix:
|
||||
ValueError
|
||||
If matrices are not rectangular or dimensions are incompatible.
|
||||
"""
|
||||
|
||||
def _rect(mat: Matrix) -> bool:
|
||||
return all(len(row) == len(mat[0]) for row in mat)
|
||||
|
||||
@@ -94,22 +93,23 @@ def transpose(matrix: Matrix) -> Matrix:
|
||||
def rot_2D(theta: float) -> list[list[float]]:
|
||||
"""Return the 2‑D rotation matrix for angle *theta* in radians.
|
||||
|
||||
The matrix is
|
||||
``[[cos(θ), -sin(θ)],
|
||||
[sin(θ), cos(θ)]]``
|
||||
where θ is interpreted as a clockwise rotation.
|
||||
The matrix is
|
||||
``[[cos(θ), -sin(θ)],
|
||||
[sin(θ), cos(θ)]]``
|
||||
where θ is interpreted as a clockwise rotation.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
theta : float
|
||||
Rotation angle in radians (clockwise).
|
||||
Parameters
|
||||
----------
|
||||
theta : float
|
||||
Rotation angle in radians (clockwise).
|
||||
|
||||
Returns
|
||||
-------
|
||||
list[list[float]]
|
||||
2x2 rotation matrix.
|
||||
Returns
|
||||
-------
|
||||
list[list[float]]
|
||||
2x2 rotation matrix.
|
||||
"""
|
||||
import math
|
||||
|
||||
# Treat theta as radians directly
|
||||
rad = theta
|
||||
cos_t = math.cos(rad)
|
||||
@@ -143,6 +143,7 @@ def rotate(matrix: Matrix, degrees: float) -> Matrix:
|
||||
n_rows, n_cols = len(matrix), len(matrix[0])
|
||||
# rotation matrix
|
||||
import math
|
||||
|
||||
r = rot_2D(math.radians(degrees))
|
||||
cos_t, sin_t = r[0][0], r[1][0] # cos and sin from 2x2 matrix
|
||||
# centre of the matrix (half‑index)
|
||||
@@ -165,6 +166,40 @@ def rotate(matrix: Matrix, degrees: float) -> Matrix:
|
||||
result[new_i][new_j] = matrix[i][j]
|
||||
return result
|
||||
|
||||
|
||||
def rot_3D(angle: float, axis: str) -> list[list[float]]:
|
||||
"""Return a 3×3 rotation matrix for a rotation around *axis*.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
angle : float
|
||||
Rotation angle in radians.
|
||||
axis : str
|
||||
Axis of rotation, one of "x", "y" or "z".
|
||||
|
||||
Returns
|
||||
-------
|
||||
list[list[float]]
|
||||
The 3×3 rotation matrix.
|
||||
|
||||
Raises
|
||||
------
|
||||
ValueError
|
||||
If *axis* is not one of "x", "y" or "z".
|
||||
"""
|
||||
import math
|
||||
|
||||
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"Unsupported rotation axis: {axis}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# matmul tests
|
||||
a1 = [[1, 2], [3, 4]]
|
||||
@@ -172,7 +207,9 @@ if __name__ == "__main__":
|
||||
assert matmul(a1, b1) == [[19, 22], [43, 50]], "matmul example 1 failed"
|
||||
a2 = [[1], [2], [3]]
|
||||
b2 = [[4, 5, 6]]
|
||||
assert matmul(a2, b2) == [[4, 5, 6], [8, 10, 12], [12, 15, 18]], "matmul example 2 failed"
|
||||
assert matmul(a2, b2) == [[4, 5, 6], [8, 10, 12], [12, 15, 18]], (
|
||||
"matmul example 2 failed"
|
||||
)
|
||||
|
||||
# transpose test
|
||||
mat = [[1, 2, 3], [4, 5, 6]]
|
||||
@@ -184,5 +221,5 @@ if __name__ == "__main__":
|
||||
assert rotate(mat3, 180) == [[6, 5], [4, 3], [2, 1]], "rotate 180 failed"
|
||||
assert rotate(mat3, 270) == [[2, 4, 6], [1, 3, 5]], "rotate 270 failed"
|
||||
assert rotate(mat3, 0) == mat3, "rotate 0 failed"
|
||||
|
||||
|
||||
print(tabulate(rot_2D(1.0)))
|
||||
+77
-23
@@ -20,13 +20,16 @@ Abweichendes Verhalten:
|
||||
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]}")
|
||||
sys.exit(
|
||||
"Dieses Skript braucht Python 3.11 oder neuer (tomllib). "
|
||||
f"Aktuell: {sys.version.split()[0]}"
|
||||
)
|
||||
|
||||
import argparse
|
||||
import subprocess
|
||||
@@ -54,7 +57,9 @@ def resolve_group(groups: dict, name: str, seen: set[str] | None = None) -> list
|
||||
return result
|
||||
|
||||
|
||||
def collect(data: dict, extras: list[str], groups: list[str], no_main: bool) -> list[str]:
|
||||
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", {})
|
||||
@@ -74,18 +79,44 @@ def collect(data: dict, extras: list[str], groups: list[str], no_main: bool) ->
|
||||
|
||||
|
||||
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 = 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")
|
||||
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():
|
||||
@@ -104,18 +135,32 @@ def main() -> int:
|
||||
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)
|
||||
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]
|
||||
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"
|
||||
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")
|
||||
@@ -127,17 +172,26 @@ def main() -> int:
|
||||
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"):
|
||||
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:
|
||||
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)])
|
||||
return subprocess.call(
|
||||
[sys.executable, "-m", "pip", "install", "-r", str(tmp_path)]
|
||||
)
|
||||
finally:
|
||||
tmp_path.unlink(missing_ok=True)
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
|
||||
import pygame
|
||||
|
||||
from compute import matmul, rot_2D
|
||||
@@ -11,7 +10,6 @@ WHITE = (255, 255, 255)
|
||||
BLUE = (0, 0, 255)
|
||||
|
||||
|
||||
|
||||
class Moon(Game):
|
||||
"""Der Mond kreist um die Erde."""
|
||||
|
||||
@@ -20,7 +18,7 @@ class Moon(Game):
|
||||
title: str = "Moon",
|
||||
fps: int = 60,
|
||||
size: tuple[int, int] = (640, 400),
|
||||
) -> None:
|
||||
) -> None:
|
||||
"""Legt Startposition, Drehwinkel und Rotationsmatrix fest."""
|
||||
super().__init__(title, fps, size)
|
||||
self.position_moon: tuple[float, float] = (
|
||||
@@ -30,8 +28,6 @@ class Moon(Game):
|
||||
self.theta = 0.05
|
||||
self.rot_moon = rot_2D(self.theta)
|
||||
|
||||
|
||||
|
||||
def update_game(self) -> bool:
|
||||
"""Dreht den Mond ein Stück weiter."""
|
||||
self.move_moon()
|
||||
@@ -46,23 +42,28 @@ class Moon(Game):
|
||||
point = [[dx], [dy]]
|
||||
result = matmul(self.rot_moon, point)
|
||||
# new absolute position
|
||||
self.position_moon = (earth_center[0] + result[0][0], earth_center[1] + result[1][0])
|
||||
self.position_moon = (
|
||||
earth_center[0] + result[0][0],
|
||||
earth_center[1] + result[1][0],
|
||||
)
|
||||
|
||||
def draw_game(self) -> None:
|
||||
"""Zeichnet Erde und Mond."""
|
||||
self.screen.fill(BLACK)
|
||||
earth_pos = (self.size[0] // 2, self.size[1] // 2)
|
||||
pygame.draw.circle(self.screen, BLUE, earth_pos, EARTH_RADIUS)
|
||||
pygame.draw.circle(self.screen, WHITE, (int(self.position_moon[0]), int(self.position_moon[1])), MOON_RADIUS)
|
||||
|
||||
|
||||
pygame.draw.circle(
|
||||
self.screen,
|
||||
WHITE,
|
||||
(int(self.position_moon[0]), int(self.position_moon[1])),
|
||||
MOON_RADIUS,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
moon = Moon()
|
||||
moon.run()
|
||||
moon = Moon()
|
||||
moon.run()
|
||||
|
||||
|
||||
|
||||
#source .venv/bin/activate
|
||||
#python moon.py
|
||||
# source .venv/bin/activate
|
||||
# python moon.py
|
||||
Whitespace-only changes.
@@ -0,0 +1,51 @@
|
||||
import math
|
||||
import pytest
|
||||
from compute import rot_2D, rot_3D
|
||||
|
||||
|
||||
def test_rot_2D_winkel_null():
|
||||
# Arrange
|
||||
winkel = 0
|
||||
erwartet = [[1, 0], [0, 1]]
|
||||
# Act
|
||||
ergebnis = rot_2D(winkel)
|
||||
# Assert
|
||||
assert ergebnis == erwartet
|
||||
|
||||
|
||||
def test_rot_2D_winkel_90():
|
||||
# Arrange
|
||||
winkel = math.pi / 2
|
||||
erwartet = [[0, -1], [1, 0]]
|
||||
# Act
|
||||
ergebnis = rot_2D(winkel)
|
||||
# Assert
|
||||
assert ergebnis[0] == pytest.approx(erwartet[0]) and ergebnis[1] == pytest.approx(
|
||||
erwartet[1]
|
||||
)
|
||||
|
||||
|
||||
def test_rot_3D_winkel_null():
|
||||
# Arrange
|
||||
winkel = 0
|
||||
achse = "z"
|
||||
erwartet = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
|
||||
# Act
|
||||
ergebnis = rot_3D(winkel, achse)
|
||||
# Assert
|
||||
assert ergebnis == erwartet
|
||||
|
||||
|
||||
def test_rot_3D_winkel_90():
|
||||
# Arrange
|
||||
winkel = math.pi / 2
|
||||
achse = "z"
|
||||
erwartet = [[0, -1, 0], [1, 0, 0], [0, 0, 1]]
|
||||
# Act
|
||||
ergebnis = rot_3D(winkel, achse)
|
||||
# Assert
|
||||
assert (
|
||||
ergebnis[0] == pytest.approx(erwartet[0])
|
||||
and ergebnis[1] == pytest.approx(erwartet[1])
|
||||
and ergebnis[2] == pytest.approx(erwartet[2])
|
||||
)
|
||||
Reference in new issue
Block a user