80_linalg.py 14 KB

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