80_linalg.py 14 KB

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