164 lines
4.7 KiB
Python
164 lines
4.7 KiB
Python
|
|
from collections.abc import Sequence
|
|
import math
|
|
|
|
Number = float | int
|
|
Matrix = Sequence[Sequence[Number]]
|
|
|
|
|
|
def _to_clean_matrix(matrix: Matrix, name: str = "Matrix") -> list[list[Number]]:
|
|
"""Hilfsfunktion: Validiert die Matrixform und wandelt sie in eine Liste von Listen um."""
|
|
rows = [list(row) for row in matrix]
|
|
if not rows:
|
|
raise ValueError(f"{name} darf nicht leer sein.")
|
|
|
|
row_len = len(rows[0])
|
|
if row_len == 0:
|
|
raise ValueError(f"{name} darf keine leeren Zeilen enthalten.")
|
|
|
|
if not all(len(row) == row_len for row in rows):
|
|
raise ValueError(f"Alle Zeilen von {name} müssen die gleiche Länge haben.")
|
|
|
|
return rows
|
|
|
|
|
|
def matmul(a: Matrix, b: Matrix) -> list[list[Number]]:
|
|
"""Multipliziert zwei 2D-Matrizen a und b."""
|
|
a_rows = _to_clean_matrix(a, name="Matrix A")
|
|
b_rows = _to_clean_matrix(b, name="Matrix B")
|
|
|
|
m = len(a_rows)
|
|
k_a = len(a_rows[0])
|
|
k_b = len(b_rows)
|
|
n = len(b_rows[0])
|
|
|
|
if k_a != k_b:
|
|
raise ValueError(
|
|
f"Inkompatible Dimensionen für Matrizenmultiplikation: "
|
|
f"({m}x{k_a}) kann nicht mit ({k_b}x{n}) multipliziert werden."
|
|
)
|
|
|
|
result: list[list[Number]] = []
|
|
for i in range(m):
|
|
row: list[Number] = []
|
|
for j in range(n):
|
|
val = sum(a_rows[i][p] * b_rows[p][j] for p in range(k_a))
|
|
row.append(val)
|
|
result.append(row)
|
|
|
|
return result
|
|
|
|
|
|
def transpose(matrix: Matrix) -> list[list[Number]]:
|
|
"""Transponiert eine 2D-Matrix."""
|
|
rows = _to_clean_matrix(matrix, name="Matrix")
|
|
return [list(col) for col in zip(*rows)]
|
|
|
|
|
|
def rot_2d(matrix_or_vec: Sequence[Number] | Matrix, angle_rad: float | None = None) -> list[Number] | list[
|
|
list[Number]]:
|
|
"""Rotiert entweder einen 2D-Vektor um angle_rad oder eine Matrix um 90 Grad."""
|
|
# Falls als 2D-Vektor aufgerufen: rot_2d([x, y], angle_rad)
|
|
if angle_rad is not None:
|
|
if len(matrix_or_vec) != 2:
|
|
raise ValueError("rot_2d für Vektoren erwartet genau 2 Elemente [x, y].")
|
|
x, y = matrix_or_vec[0], matrix_or_vec[1]
|
|
cos_a = math.cos(angle_rad)
|
|
sin_a = math.sin(angle_rad)
|
|
return [x * cos_a - y * sin_a, x * sin_a + y * cos_a]
|
|
|
|
# Falls als Matrix aufgerufen: rot_2d(matrix)
|
|
rows = _to_clean_matrix(matrix_or_vec, name="Matrix")
|
|
return [list(col) for col in zip(*rows[::-1])]
|
|
|
|
|
|
def rot_3d(angle: float, axis: str) -> list[list[float]]:
|
|
"""Erzeugt eine 3D-Rotationsmatrix für die Rotation um eine gegebene Achse.
|
|
|
|
Formeln der Rotationsmatrizen:
|
|
------------------------------
|
|
Rotation um die x-Achse:
|
|
R_x(θ) = [
|
|
[1, 0, 0],
|
|
[0, cos(θ), -sin(θ)],
|
|
[0, sin(θ), cos(θ)]
|
|
]
|
|
|
|
Rotation um die y-Achse:
|
|
R_y(θ) = [
|
|
[ cos(θ), 0, sin(θ)],
|
|
[ 0, 1, 0],
|
|
[-sin(θ), 0, cos(θ)]
|
|
]
|
|
|
|
Rotation um die z-Achse:
|
|
R_z(θ) = [
|
|
[cos(θ), -sin(θ), 0],
|
|
[sin(θ), cos(θ), 0],
|
|
[ 0, 0, 1]
|
|
]
|
|
|
|
Parameters
|
|
----------
|
|
angle : float
|
|
Rotationswinkel θ im Bogenmaß (Radiant).
|
|
axis : str
|
|
Rotationsachse; gültige Werte sind 'x', 'y' oder 'z'.
|
|
|
|
Returns
|
|
-------
|
|
list[list[float]]
|
|
Die 3x3-Rotationsmatrix als Liste von Listen.
|
|
|
|
Raises
|
|
------
|
|
ValueError
|
|
Wenn ein ungültiger Achsenbezeichner übergeben wird.
|
|
"""
|
|
c = math.cos(angle)
|
|
s = math.sin(angle)
|
|
axis_norm = axis.strip().lower()
|
|
|
|
if axis_norm == "x":
|
|
return [
|
|
[1.0, 0.0, 0.0],
|
|
[0.0, c, -s],
|
|
[0.0, s, c],
|
|
]
|
|
elif axis_norm == "y":
|
|
return [
|
|
[c, 0.0, s],
|
|
[0.0, 1.0, 0.0],
|
|
[-s, 0.0, c],
|
|
]
|
|
elif axis_norm == "z":
|
|
return [
|
|
[c, -s, 0.0],
|
|
[s, c, 0.0],
|
|
[0.0, 0.0, 1.0],
|
|
]
|
|
else:
|
|
raise ValueError(f"Ungültige Achse '{axis}'. Gültige Werte sind 'x', 'y' oder 'z'.")
|
|
|
|
def project_ortho(
|
|
point: tuple[float, float, float], scale: float = 1
|
|
) -> tuple[float, float]:
|
|
"""Projiziert einen 3D-Punkt orthogonal auf eine 2D-Ebene und skaliert ihn optional.
|
|
|
|
Die z-Koordinate wird ignoriert. Die verbleibenden x- und y-Koordinaten
|
|
werden mit dem Skalierungsfaktor multipliziert.
|
|
|
|
Parameters
|
|
----------
|
|
point : tuple[float, float, float]
|
|
Die 3D-Koordinaten (x, y, z).
|
|
scale : float, default=1
|
|
Der Skalierungsfaktor.
|
|
|
|
Returns
|
|
-------
|
|
tuple[float, float]
|
|
Die projizierten und skalierten 2D-Koordinaten (x * scale, y * scale).
|
|
"""
|
|
x, y, _ = point
|
|
return float(x * scale), float(y * scale) |