80_linalg.py 17 KB

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