80_linalg.py 15 KB

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