80_linalg.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. from linalg import mat3x3, vec2, vec3
  2. import random
  3. import sys
  4. import math
  5. a = vec2(1.5, 2)
  6. assert a.x == 1.5
  7. assert a.y == 2
  8. assert repr(math) == "<module 'math'>"
  9. # 出于对精度转换的考虑,在本测试中具体将采用str(floating_num)[:6]来比较两个浮点数是否相等
  10. # test vec2--------------------------------------------------------------------
  11. def rotated_vec2(vec_2: vec2, radians: float):
  12. cos_theta = math.cos(radians)
  13. sin_theta = math.sin(radians)
  14. new_x = vec_2.x * cos_theta - vec_2.y * sin_theta
  15. new_y = vec_2.x * sin_theta + vec_2.y * cos_theta
  16. return vec2(new_x, new_y)
  17. # 生成随机测试目标
  18. min_num = -10.0
  19. max_num = 10.0
  20. test_vec2 = vec2(*tuple([random.uniform(min_num, max_num) for _ in range(2)]))
  21. test_vec2_2 = vec2(*tuple([random.uniform(min_num, max_num) for _ in range(2)]))
  22. static_test_vec2_float = vec2(3.18, -1.09)
  23. static_test_vec2_int = vec2(278, -1391)
  24. # test __repr__
  25. assert str(static_test_vec2_float).startswith('vec2(')
  26. assert str(static_test_vec2_int).startswith('vec2(')
  27. # test copy
  28. element_name_list = [e for e in dir(test_vec2) if e in 'x,y,z,w']
  29. element_value_list = [getattr(test_vec2, attr) for attr in element_name_list]
  30. copy_element_value_list = [getattr(test_vec2, attr) for attr in element_name_list]
  31. assert element_value_list == copy_element_value_list
  32. # test rotate
  33. test_vec2_copy = test_vec2
  34. radians = random.uniform(-10*math.pi, 10*math.pi)
  35. test_vec2_copy = rotated_vec2(test_vec2_copy, radians)
  36. res = test_vec2.rotate(radians)
  37. assert (res == test_vec2_copy), (res, test_vec2_copy, test_vec2)
  38. # test smooth_damp
  39. vel = vec2(0, 0)
  40. ret, vel = vec2.smooth_damp(vec2(1, 2), vec2(3, 4), vel, 0.2, 0.001, 0.05)
  41. assert isinstance(ret, vec2)
  42. assert vel.length() > 0
  43. # test vec3--------------------------------------------------------------------
  44. # 生成随机测试目标
  45. min_num = -10.0
  46. max_num = 10.0
  47. test_vec3 = vec3(*tuple([random.uniform(min_num, max_num) for _ in range(3)]))
  48. static_test_vec3_float = vec3(3.1886954323, -1098399.59932453432, 9.00000000000002765)
  49. static_test_vec3_int = vec3(278, -13919730938747, 1364223456756456)
  50. # test __repr__
  51. assert str(static_test_vec3_float).startswith('vec3(')
  52. assert str(static_test_vec3_int).startswith('vec3(')
  53. # test copy
  54. element_name_list = ['x', 'y', 'z']
  55. element_value_list = [getattr(test_vec3, attr) for attr in element_name_list]
  56. copy_element_value_list = [getattr(test_vec3, attr) for attr in element_name_list]
  57. assert element_value_list == copy_element_value_list
  58. # test mat3x3--------------------------------------------------------------------
  59. def mat_to_str_list(mat):
  60. ret = [[0,0,0], [0,0,0], [0,0,0]]
  61. for i in range(3):
  62. for j in range(3):
  63. ret[i][j] = str(round(mat[i, j], 2))[:6]
  64. return ret
  65. def mat_list_to_str_list(mat_list):
  66. ret = [[0,0,0], [0,0,0], [0,0,0]]
  67. for i in range(3):
  68. for j in range(3):
  69. ret[i][j] = str(round(mat_list[i][j], 2))[:6]
  70. return ret
  71. def mat_to_list(mat):
  72. ret = [[0,0,0], [0,0,0], [0,0,0]]
  73. for i in range(3):
  74. for j in range(3):
  75. ret[i][j] = mat[i, j]
  76. return ret
  77. def mat_round(mat, pos):
  78. '''
  79. 对mat的副本的每一个元素执行round(element, pos),返回副本
  80. 用于校对元素是浮点数的矩阵
  81. '''
  82. ret = mat.copy()
  83. for i, row in enumerate(ret):
  84. for j, element in enumerate(row):
  85. row[j] = round(element, pos)
  86. ret[i] = row
  87. return ret
  88. def get_row(mat, row_index):
  89. '''
  90. 返回mat的row_index行元素构成的列表
  91. '''
  92. ret = []
  93. for i in range(3):
  94. ret.append(mat[row_index, i])
  95. return ret
  96. def get_col(mat, col_index):
  97. '''
  98. 返回mat的col_index列元素构成的列表
  99. '''
  100. ret = []
  101. for i in range(3):
  102. ret.append(mat[i, col_index])
  103. return ret
  104. def calculate_inverse(matrix):
  105. '''
  106. 返回逆矩阵
  107. '''
  108. # 获取矩阵的行数和列数
  109. rows = len(matrix)
  110. cols = len(matrix[0])
  111. # 确保矩阵是方阵
  112. if rows != cols:
  113. raise ValueError("输入矩阵必须是方阵")
  114. # 构建单位矩阵
  115. identity = [[1 if i == j else 0 for j in range(cols)] for i in range(rows)]
  116. # 将单位矩阵与输入矩阵进行初等行变换
  117. augmented_matrix = [row + identity[i] for i, row in enumerate(matrix)]
  118. # 初等行变换,将输入矩阵转化为单位矩阵,同时在另一边进行相同的行变换
  119. for i in range(cols):
  120. pivot = augmented_matrix[i][i]
  121. if pivot == 0:
  122. raise ValueError("输入矩阵不可逆")
  123. scale_row(augmented_matrix, i, 1/pivot)
  124. for j in range(cols):
  125. if j != i:
  126. scale = augmented_matrix[j][i]
  127. row_operation(augmented_matrix, j, i, -scale)
  128. # 提取逆矩阵
  129. inverse_matrix = [row[cols:] for row in augmented_matrix]
  130. return inverse_matrix
  131. def scale_row(matrix, row, scale):
  132. matrix[row] = [element * scale for element in matrix[row]]
  133. def row_operation(matrix, target_row, source_row, scale):
  134. matrix[target_row] = [target_element + scale * source_element for target_element, source_element in zip(matrix[target_row], matrix[source_row])]
  135. # 生成随机测试目标
  136. min_num = -10.0
  137. max_num = 10.0
  138. test_mat = mat3x3([random.uniform(min_num, max_num) for _ in range(9)])
  139. static_test_mat_float= mat3x3(
  140. 7.264189733952545, -5.432187523625671, 1.8765304152872613,
  141. -2.4910524352374734, 8.989660807513068, -0.7168824333280513,
  142. 9.558042327611506, -3.336280256662496, 4.951381528057387
  143. )
  144. static_test_mat_float_inv = mat3x3( 0.32265243, 0.15808159, -0.09939472,
  145. 0.04199553, 0.13813096, 0.00408326,
  146. -0.59454451, -0.21208362, 0.39658464)
  147. static_test_mat_int = mat3x3([
  148. 1, 2, 3,
  149. 4, 5, 6,
  150. 7, 8, 9]
  151. )
  152. # test incorrect number of parameters is passed
  153. for i in range(20):
  154. if i in [0, 9]:
  155. continue
  156. try:
  157. test_mat_copy = mat3x3(*tuple([e+0.1 for e in range(i)]))
  158. # 既然参数数量不是合法的0个或9个,并且这里也没有触发TypeError,那么引发测试失败
  159. print(f'When there are {i} arguments, no TypeError is triggered')
  160. exit(1)
  161. except TypeError:
  162. pass
  163. # test 9 floating parameters is passed
  164. test_mat_copy = test_mat.copy()
  165. element_name_list = []
  166. for i in range(3):
  167. for j in range(3):
  168. element_name_list.append(f'_{i+1}{j+1}')
  169. element_value_list = [getattr(test_mat, attr) for attr in element_name_list]
  170. assert mat3x3(*tuple(element_value_list)) == test_mat
  171. # test copy
  172. test_mat_copy = test_mat.copy()
  173. assert test_mat is not test_mat_copy
  174. assert test_mat == test_mat_copy
  175. # test __getitem__
  176. for i, element in enumerate([getattr(test_mat, e) for e in element_name_list]):
  177. assert test_mat[int(i/3), i%3] == element
  178. try:
  179. test_mat[1,2,3]
  180. raise Exception('未能触发错误拦截, 此处应当报错 IndexError("index out of range")')
  181. except:
  182. pass
  183. try:
  184. test_mat[-1][4]
  185. raise Exception('未能触发错误拦截, 此处应当报错 IndexError("index out of range")')
  186. except:
  187. pass
  188. # test __setitem__
  189. test_mat_copy = test_mat.copy()
  190. for i, element in enumerate([getattr(test_mat_copy, e) for e in element_name_list]):
  191. test_mat_copy[int(i/3), i%3] = list(range(9))[i]
  192. assert test_mat_copy == mat3x3([0,1,2,
  193. 3,4,5,
  194. 6,7,8])
  195. try:
  196. test_mat[1,2,3] = 1
  197. raise Exception('未能触发错误拦截, 此处应当报错 TypeError("Mat3x3.__setitem__ takes a tuple of 2 integers")')
  198. except:
  199. pass
  200. try:
  201. test_mat[-1][4] = 1
  202. raise Exception('未能触发错误拦截, 此处应当报错 IndexError("index out of range")')
  203. except:
  204. pass
  205. # test __add__
  206. test_mat_copy = test_mat.copy()
  207. ones = mat3x3.ones()
  208. result_mat = test_mat_copy.__add__(ones)
  209. correct_result_mat = test_mat_copy.copy()
  210. for i in range(3):
  211. for j in range(3):
  212. correct_result_mat[i, j] += 1
  213. assert result_mat == correct_result_mat
  214. # test __sub__
  215. test_mat_copy = test_mat.copy()
  216. ones = mat3x3.ones()
  217. result_mat = test_mat_copy.__sub__(ones)
  218. correct_result_mat = test_mat_copy.copy()
  219. for i in range(3):
  220. for j in range(3):
  221. correct_result_mat[i, j] -= 1
  222. assert result_mat == correct_result_mat
  223. # test __mul__
  224. test_mat_copy = test_mat.copy()
  225. result_mat = test_mat_copy.__mul__(12.345)
  226. correct_result_mat = test_mat_copy.copy()
  227. for i in range(3):
  228. for j in range(3):
  229. correct_result_mat[i, j] *= 12.345
  230. # print(result_mat)
  231. # print(correct_result_mat)
  232. assert result_mat == correct_result_mat
  233. # test matmul
  234. test_mat_copy = test_mat.copy()
  235. test_mat_copy_2 = test_mat.copy()
  236. result_mat = test_mat_copy @ test_mat_copy_2
  237. correct_result_mat = mat3x3()
  238. for i in range(3):
  239. for j in range(3):
  240. correct_result_mat[i, j] = sum([e1*e2 for e1, e2 in zip(get_row(test_mat_copy, i), get_col(test_mat_copy_2, j))])
  241. assert result_mat == correct_result_mat
  242. # test determinant
  243. test_mat_copy = test_mat.copy()
  244. test_mat_copy.determinant()
  245. # test __repr__
  246. assert str(static_test_mat_float)
  247. assert str(static_test_mat_int)
  248. # test __truediv__
  249. test_mat_copy = test_mat.copy()
  250. result_mat = test_mat_copy.__truediv__(12.345)
  251. correct_result_mat = test_mat_copy.copy()
  252. for i in range(3):
  253. for j in range(3):
  254. correct_result_mat[i, j] /= 12.345
  255. assert result_mat == correct_result_mat
  256. # test __rmul__
  257. test_mat_copy = test_mat.copy()
  258. result_mat = 12.345 * test_mat_copy
  259. correct_result_mat = test_mat_copy.copy()
  260. for i in range(3):
  261. for j in range(3):
  262. correct_result_mat[i, j] *= 12.345
  263. assert result_mat == correct_result_mat
  264. # 此处测试不完全, 未验证正确性
  265. # test interface of "@" "matmul" "__matmul__" with vec3 and error handling
  266. test_mat_copy = test_mat.copy()
  267. test_mat_copy @ vec3(83,-9.12, 0.2983)
  268. try:
  269. test_mat_copy @ 12345
  270. exit(1)
  271. except TypeError:
  272. pass
  273. # test transpose
  274. test_mat_copy = test_mat.copy()
  275. assert test_mat_copy.transpose_() is None
  276. assert test_mat_copy == test_mat.transpose()
  277. assert test_mat_copy.transpose() == test_mat_copy.transpose().transpose().transpose()
  278. # test inverse
  279. assert ~static_test_mat_float == static_test_mat_float_inv == static_test_mat_float.inverse()
  280. assert static_test_mat_float.inverse_() is None
  281. assert static_test_mat_float == static_test_mat_float_inv
  282. try:
  283. ~mat3x3([1, 2, 3, 2, 4, 6, 3, 6, 9])
  284. raise Exception('未能拦截错误 ValueError("matrix is not invertible") 在 test_mat_copy 的行列式为0')
  285. except ValueError:
  286. pass
  287. # test zeros
  288. assert mat3x3([0 for _ in range(9)]) == mat3x3.zeros()
  289. # test ones
  290. assert mat3x3([1 for _ in range(9)]) == mat3x3.ones()
  291. # test identity
  292. assert mat3x3([1,0,0,0,1,0,0,0,1]) == mat3x3.identity()
  293. # test affine transformations-----------------------------------------------
  294. # test trs
  295. def trs(t, radian, s):
  296. cr = math.cos(radian)
  297. sr = math.sin(radian)
  298. elements = [[s[0] * cr, -s[1] * sr, t[0]],
  299. [s[0] * sr, s[1] * cr, t[1]],
  300. [0.0, 0.0, 1.0]]
  301. return elements
  302. test_vec2_copy = test_vec2
  303. test_vec2_2_copy = test_vec2_2
  304. test_vec2_list = [test_vec2_copy.x, test_vec2_copy.y]
  305. test_vec2_2_list = [test_vec2_2_copy.x, test_vec2_2_copy.y]
  306. radian = random.uniform(-10*math.pi, 10*math.pi)
  307. mat3x3.trs(test_vec2_copy, radian, test_vec2_2_copy)
  308. a = mat3x3.zeros()
  309. a.copy_trs_(test_vec2_copy, radian, test_vec2_2_copy)
  310. assert a == mat3x3.trs(test_vec2_copy, radian, test_vec2_2_copy)
  311. b = mat3x3.identity()
  312. b.copy_t_(test_vec2_copy)
  313. b.copy_r_(radian)
  314. b.copy_s_(test_vec2_2_copy)
  315. assert a == b
  316. # test is_affine
  317. def mat_is_affine(mat_list):
  318. return mat_list[2][0] == 0 and mat_list[2][1] == 0 and mat_list[2][2] == 1
  319. # 通过random.unifrom的返回值不可能是整数0或1, 因此认为test_mat不可能is_affine
  320. test_mat_copy = test_mat.copy()
  321. assert test_mat_copy.is_affine() == mat_is_affine(mat_to_list(test_mat_copy))
  322. test_mat_copy[2,0] = 0
  323. test_mat_copy[2,1] = 0
  324. test_mat_copy[2,2] = 1
  325. assert test_mat_copy.is_affine() == mat_is_affine(mat_to_list(test_mat_copy))
  326. # test translation
  327. test_mat_copy = test_mat.copy()
  328. assert test_mat_copy._t() == vec2(test_mat_copy[0, 2], test_mat_copy[1, 2])
  329. # 该方法的测试未验证计算的准确性
  330. # test rotation
  331. test_mat_copy = test_mat.copy()
  332. assert type(test_mat_copy._r()) is float
  333. # test scale
  334. test_mat_copy = test_mat.copy()
  335. temp_vec2 = test_mat_copy._s()
  336. # test transform_point
  337. test_mat_copy = test_mat.copy()
  338. test_mat_copy = test_mat.copy()
  339. test_vec2_copy = test_vec2
  340. temp_vec2 = test_mat_copy.transform_point(test_vec2_copy)
  341. # test transform_vector
  342. test_mat_copy = test_mat.copy()
  343. test_mat_copy = test_mat.copy()
  344. test_vec2_copy = test_vec2
  345. temp_vec2 = test_mat_copy.transform_vector(test_vec2_copy)
  346. # test inverse_transform_point
  347. assert test_mat_copy.inverse_transform_point(test_vec2_copy) == test_mat_copy.inverse().transform_point(test_vec2_copy)
  348. # test inverse_transform_vector
  349. assert test_mat_copy.inverse_transform_vector(test_vec2_copy) == test_mat_copy.inverse().transform_vector(test_vec2_copy)
  350. val = vec2.angle(vec2(-1, 0), vec2(0, -1))
  351. assert 1.57 < val < 1.58
  352. # test about staticmethod
  353. class mymat3x3(mat3x3):
  354. def f(self):
  355. _0 = self.zeros()
  356. _1 = super().zeros()
  357. _2 = mat3x3.zeros()
  358. return _0 == _1 == _2
  359. assert mymat3x3().f()
  360. d = mat3x3.identity()
  361. assert d.copy_(mat3x3.zeros()) is None
  362. assert d == mat3x3.zeros()
  363. d = mat3x3.identity()
  364. assert d.matmul(mat3x3.zeros()) == mat3x3.zeros()
  365. assert d == mat3x3.identity()
  366. assert d.matmul(mat3x3.zeros(), out=d) is None
  367. assert d == mat3x3.zeros()
  368. try:
  369. assert d[6, 6]
  370. exit(1)
  371. except IndexError:
  372. pass
  373. # test vec * vec
  374. assert vec2(1, 2) * vec2(3, 4) == vec2(3, 8)
  375. assert vec3(1, 2, 3) * vec3(4, 5, 6) == vec3(4, 10, 18)
  376. # test vec.__getitem__
  377. assert vec2(1, 2)[0] == 1 and vec2(1, 2)[1] == 2
  378. assert vec3(1, 2, 3)[0] == 1 and vec3(1, 2, 3)[1] == 2 and vec3(1, 2, 3)[2] == 3