Advertisement
lavrent

gramm-schmidt orthogonalization

Apr 27th, 2024 (edited)
718
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.55 KB | None | 0 0
  1. import math
  2. import numpy as np
  3. from typing import Any, Iterable
  4.  
  5.  
  6. def matrix_to_geolin_answer(
  7.     matrix: Iterable[Iterable[Any]], digits: int = 2, eps: float = 1e-5
  8. ) -> str:
  9.     ans = "; ".join(
  10.         [
  11.             ", ".join(
  12.                 (str(round(e)) if (abs(round(e) - e) < eps) else str(round(e, digits)))
  13.                 for e in row
  14.             )
  15.             for row in matrix
  16.         ]
  17.     )
  18.     return "[" + ans + "]"
  19.  
  20.  
  21. def gram_multiply(x: np.ndarray, y: np.ndarray, gram: np.ndarray) -> int:
  22.     return np.dot(np.dot(np.transpose(x), gram), y).astype(np.int64)
  23.  
  24.  
  25. def ortogonalize(vectors: np.ndarray, gram: np.ndarray | None = None) -> np.ndarray:
  26.     vectors = vectors.astype(np.int64)
  27.     n = vectors.shape[1]
  28.     if gram is None:
  29.         gram = np.identity(n)
  30.     gram = gram.astype(np.int64)
  31.     ans: list[np.ndarray] = []
  32.     for f in vectors:
  33.         r = f
  34.         m = 1
  35.         for g in ans:
  36.             nom = gram_multiply(f, g, gram)
  37.             denom = gram_multiply(g, g, gram)
  38.             m = math.lcm(m, denom // math.gcd(nom, denom))
  39.             r = np.subtract(r, np.dot(nom / denom, g))
  40.         ans.append(np.round(r * m).astype(np.int64))
  41.     return np.array(ans)
  42.  
  43.  
  44. vectors = np.array([[1, -1, -1, 2, 3], [-1, 2, 2, -6, -5], [1, -1, -2, 3, 5]])
  45. gram = np.array(
  46.     [
  47.         [4, -2, 2, -2, 2],
  48.         [-2, 12, -2, -2, -2],
  49.         [2, -2, 4, -6, 2],
  50.         [-2, -2, -6, 12, -2],
  51.         [2, -2, 2, -2, 2],
  52.     ]
  53. )
  54. ans = ortogonalize(vectors, gram)
  55. print(ans)
  56. print(matrix_to_geolin_answer(ans))
  57.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement