Compare commits
5
Commits
c6ce4d71f5
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f54fc5d4ef | ||
|
|
9aa475906e | ||
|
|
f1861b4a39 | ||
|
|
503d738c00 | ||
|
|
b5b9bfb5f0 |
No files matched your search
@@ -0,0 +1,6 @@
|
||||
.venv/
|
||||
__pycache__/
|
||||
.pytest_cache/
|
||||
.ruff_cache/
|
||||
.idea/
|
||||
*.pyc
|
||||
@@ -0,0 +1,4 @@
|
||||
# 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`.
|
||||
-143
@@ -1,143 +0,0 @@
|
||||
"""
|
||||
Matrix multiplication for nested list matrices.
|
||||
|
||||
This module contains the :func:`matmul` function, which multiplies two
|
||||
matrices represented as nested Python lists. The matrices are
|
||||
expected to be rectangular (each sub‑list has the same length). A
|
||||
:class:`ValueError` is raised if the inner dimensions do not match.
|
||||
|
||||
Example
|
||||
-------
|
||||
>>> a = [[1, 2], [3, 4]]
|
||||
>>> b = [[5, 6], [7, 8]]
|
||||
>>> matmul(a, b)
|
||||
[[19.0, 22.0], [43.0, 50.0]]
|
||||
|
||||
The function is intentionally simple and performs no type checking
|
||||
of the inner elements; it simply forwards the arithmetic operations to
|
||||
Python's built‑in integer and float handling.
|
||||
"""
|
||||
|
||||
import math
|
||||
|
||||
|
||||
def rot_2D(theta: float) -> list[list[float]]:
|
||||
"""Return the 2‑D rotation matrix for a given angle.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
theta : float
|
||||
Angle in radians to rotate counter‑clockwise around the origin.
|
||||
|
||||
Returns
|
||||
-------
|
||||
list[list[float]]
|
||||
2x2 rotation matrix
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> rot_2D(0) # identity
|
||||
[[1.0, -0.0], [0.0, 1.0]]
|
||||
"""
|
||||
c = math.cos(theta)
|
||||
s = math.sin(theta)
|
||||
return [[c, -s], [s, c]]
|
||||
|
||||
|
||||
def matmul(a: list[list[float | int]], b: list[list[float | int]]) -> list[list[float]]:
|
||||
"""Return the matrix product of *a* and *b*.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
a : list[list[float | int]]
|
||||
First matrix, shape ``(m, n)``.
|
||||
b : list[list[float | int]]
|
||||
Second matrix, shape ``(n, p)``.
|
||||
|
||||
Returns
|
||||
-------
|
||||
list[list[float]]
|
||||
The result matrix of shape ``(m, p)``.
|
||||
|
||||
Raises
|
||||
------
|
||||
ValueError
|
||||
If the number of columns of ``a`` does not equal the number of
|
||||
rows of ``b``.
|
||||
"""
|
||||
n_cols_a = len(a[0]) if a else 0
|
||||
n_rows_b = len(b)
|
||||
if n_cols_a != n_rows_b:
|
||||
raise ValueError(
|
||||
f"inner dimensions must match: {n_cols_a} (a columns) != {n_rows_b} (b rows)"
|
||||
)
|
||||
|
||||
m = len(a)
|
||||
p = len(b[0]) if b else 0
|
||||
# Pre‑allocate result matrix
|
||||
result: list[list[float]] = [[0.0 for _ in range(p)] for _ in range(m)]
|
||||
|
||||
for i in range(m):
|
||||
for k in range(n_cols_a): # using k as column index of a, row of b
|
||||
a_val = a[i][k]
|
||||
for j in range(p):
|
||||
result[i][j] += a_val * b[k][j]
|
||||
return result
|
||||
|
||||
|
||||
|
||||
def transpose(matrix: list[list[float | int]]) -> list[list[float | int]]:
|
||||
"""Return the transpose of the given matrix.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
matrix : list[list[float | int]]
|
||||
Matrix to transpose. All rows must have the same length.
|
||||
|
||||
Returns
|
||||
-------
|
||||
list[list[float | int]]
|
||||
Transposed matrix.
|
||||
|
||||
Raises
|
||||
------
|
||||
ValueError
|
||||
If ``matrix`` is empty or rows have differing lengths.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> mat = [[1, 2, 3], [4, 5, 6]]
|
||||
>>> transpose(mat)
|
||||
[[1, 4], [2, 5], [3, 6]]
|
||||
"""
|
||||
if not matrix:
|
||||
raise ValueError("Matrix must not be empty")
|
||||
row_length = len(matrix[0])
|
||||
if any(len(row) != row_length for row in matrix):
|
||||
raise ValueError("All rows must have the same number of columns")
|
||||
return [list(col) for col in zip(*matrix)]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
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 = [
|
||||
[1, 2, 3],
|
||||
[4, 5, 6],
|
||||
]
|
||||
|
||||
print("Transposed Matrix:\n", transpose(matrix))
|
||||
print("\nMatrix multiplication result:\n")
|
||||
matrix_c = matmul(matrix_a, matrix_b)
|
||||
for row in matrix_c:
|
||||
print(row)
|
||||
print("\nRotation matrix 90°:\n", rot_2D(math.pi/2))
|
||||
|
||||
@@ -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())
|
||||
Whitespace-only changes.
@@ -0,0 +1,176 @@
|
||||
|
||||
"""Matrixfunktionen für MatrixMania."""
|
||||
|
||||
import math
|
||||
|
||||
from tabulate import tabulate
|
||||
|
||||
|
||||
def rot_2D(theta: float) -> list[list[float]]:
|
||||
"""Berechnet eine 2D-Rotationsmatrix."""
|
||||
c = math.cos(theta)
|
||||
s = math.sin(theta)
|
||||
|
||||
return [[c, -s], [s, c]]
|
||||
|
||||
|
||||
def rot_3D(angle: float, axis: str) -> list[list[float]]:
|
||||
"""Berechnet eine 3D-Rotationsmatrix um die x-, y- oder z-Achse."""
|
||||
c = math.cos(angle)
|
||||
s = math.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 x-y-Ebene."""
|
||||
x, y, z = point
|
||||
|
||||
return (x * scale, y * scale)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# NEU: HAUSAUFGABE – PERSPEKTIVISCHE PROJEKTION
|
||||
# ============================================================
|
||||
|
||||
def project_perspective(
|
||||
point: tuple[float, float, float],
|
||||
focal_length: float = 1,
|
||||
camera_distance: float = 4.0 ,
|
||||
scale: float = 1,
|
||||
) -> tuple[float, float]:
|
||||
"""Projiziert einen 3D-Punkt perspektivisch auf die 2D-Ebene."""
|
||||
|
||||
x, y, z = point # NEU: 3D-Koordinaten auslesen
|
||||
|
||||
distance = z + camera_distance # NEU: Entfernung berechnen
|
||||
|
||||
if distance == 0: # NEU: Division durch null verhindern
|
||||
raise ValueError("Der Punkt liegt auf der Kameraebene.")
|
||||
|
||||
x_new = (x * focal_length / distance) * scale # NEU: x projizieren
|
||||
y_new = (y * focal_length / distance) * scale # NEU: y projizieren
|
||||
|
||||
return (x_new, y_new) # NEU: 2D-Koordinaten zurückgeben
|
||||
|
||||
# ============================================================
|
||||
# ENDE DER NEUEN HAUSAUFGABE
|
||||
# ============================================================
|
||||
|
||||
|
||||
def matmul(
|
||||
a: list[list[float | int]],
|
||||
b: list[list[float | int]],
|
||||
) -> list[list[float]]:
|
||||
"""Multipliziert zwei Matrizen."""
|
||||
n_cols_a = len(a[0]) if a else 0
|
||||
n_rows_b = len(b)
|
||||
|
||||
if n_cols_a != n_rows_b:
|
||||
raise ValueError(
|
||||
f"inner dimensions must match: "
|
||||
f"{n_cols_a} (a columns) != {n_rows_b} (b rows)"
|
||||
)
|
||||
|
||||
m = len(a)
|
||||
p = len(b[0]) if b else 0
|
||||
|
||||
result: list[list[float]] = [
|
||||
[0.0 for _ in range(p)] for _ in range(m)
|
||||
]
|
||||
|
||||
for i in range(m):
|
||||
for k in range(n_cols_a):
|
||||
a_val = a[i][k]
|
||||
for j in range(p):
|
||||
result[i][j] += a_val * b[k][j]
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def transpose(
|
||||
matrix: list[list[float | int]],
|
||||
) -> list[list[float | int]]:
|
||||
"""Transponiert eine Matrix."""
|
||||
if not matrix:
|
||||
raise ValueError("Matrix must not be empty")
|
||||
|
||||
row_length = len(matrix[0])
|
||||
|
||||
if any(len(row) != row_length for row in matrix):
|
||||
raise ValueError(
|
||||
"All rows must have the same number of columns"
|
||||
)
|
||||
|
||||
return [list(col) for col in zip(*matrix)]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
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 = [
|
||||
[1, 2, 3],
|
||||
[4, 5, 6],
|
||||
]
|
||||
|
||||
print("Transposed Matrix:\n", transpose(matrix))
|
||||
|
||||
print("\nMatrix multiplication result:\n")
|
||||
matrix_c = matmul(matrix_a, matrix_b)
|
||||
|
||||
for row in matrix_c:
|
||||
print(row)
|
||||
|
||||
print("\nRotation matrix 90°:\n", rot_2D(math.pi / 2))
|
||||
print(tabulate(rot_2D(1.0)))
|
||||
|
||||
print("\n3D-Rotation um die X-Achse:")
|
||||
print(tabulate(rot_3D(math.pi / 2, "x")))
|
||||
|
||||
print("\n3D-Rotation um die Y-Achse:")
|
||||
print(tabulate(rot_3D(math.pi / 2, "y")))
|
||||
|
||||
print("\n3D-Rotation um die Z-Achse:")
|
||||
print(tabulate(rot_3D(math.pi / 2, "z")))
|
||||
|
||||
# NEU: HAUSAUFGABE – Perspektivische Projektion testen
|
||||
print("\nPerspektivische Projektion:")
|
||||
print(project_perspective((1.0, 2.0, 3.0)))
|
||||
|
||||
# NEU: HAUSAUFGABE – Perspektivische Projektion mit Skalierung testen
|
||||
print("\nPerspektivische Projektion mit Skalierung 100:")
|
||||
print(project_perspective((1.0, 2.0, 3.0), scale=100))
|
||||
@@ -0,0 +1,6 @@
|
||||
[project]
|
||||
name = "matrixmania"
|
||||
version = "0.1.0"
|
||||
dependencies = ["tabulate", "ruff"]
|
||||
[project.optional-dependencies]
|
||||
dev = ["pytest", "ruff", "pytest-cov"]
|
||||
@@ -0,0 +1,52 @@
|
||||
|
||||
import pytest
|
||||
|
||||
from matrixmania.compute import project_ortho, project_perspective
|
||||
|
||||
|
||||
def test_project_ortho_default():
|
||||
# Arrange
|
||||
point = (1.0, 2.0, 3.0)
|
||||
expected = (1.0, 2.0)
|
||||
|
||||
# Act
|
||||
result = project_ortho(point)
|
||||
|
||||
# Assert
|
||||
assert result == expected
|
||||
|
||||
|
||||
def test_project_ortho_scale_100():
|
||||
# Arrange
|
||||
point = (1.0, 2.0, 3.0)
|
||||
expected = (100.0, 200.0)
|
||||
|
||||
# Act
|
||||
result = project_ortho(point, scale=100)
|
||||
|
||||
# Assert
|
||||
assert result == expected
|
||||
|
||||
|
||||
def test_project_perspective_default():
|
||||
# Arrange
|
||||
point = (1.0, 2.0, 3.0)
|
||||
expected = (1.0 / 7.0, 2.0 / 7.0)
|
||||
|
||||
# Act
|
||||
result = project_perspective(point)
|
||||
|
||||
# Assert
|
||||
assert result == pytest.approx(expected)
|
||||
|
||||
|
||||
def test_project_perspective_focal_length_2_scale_100():
|
||||
# Arrange
|
||||
point = (1.0, 2.0, 3.0)
|
||||
expected = ((1.0 * 2.0 / 7.0) * 100, (2.0 * 2.0 / 7.0) * 100)
|
||||
|
||||
# Act
|
||||
result = project_perspective(point, focal_length=2.0, scale=100)
|
||||
|
||||
# Assert
|
||||
assert result == pytest.approx(expected)
|
||||
@@ -0,0 +1,36 @@
|
||||
|
||||
import math
|
||||
|
||||
import pytest
|
||||
|
||||
from matrixmania.compute import rot_2D, rot_3D
|
||||
|
||||
|
||||
def test_rot_2D():
|
||||
# Arrange
|
||||
angle = math.pi / 2
|
||||
expected = [[0.0, -1.0], [1.0, 0.0]]
|
||||
|
||||
# Act
|
||||
result = rot_2D(angle)
|
||||
|
||||
# Assert
|
||||
for row, expected_row in zip(result, expected):
|
||||
assert row == pytest.approx(expected_row)
|
||||
|
||||
|
||||
def test_rot_3D():
|
||||
# Arrange
|
||||
angle = math.pi / 2
|
||||
expected = [
|
||||
[0.0, -1.0, 0.0],
|
||||
[1.0, 0.0, 0.0],
|
||||
[0.0, 0.0, 1.0],
|
||||
]
|
||||
|
||||
# Act
|
||||
result = rot_3D(angle, "z")
|
||||
|
||||
# Assert
|
||||
for row, expected_row in zip(result, expected):
|
||||
assert row == pytest.approx(expected_row)
|
||||
Reference in new issue
Block a user