80_linalg.py 11 KB

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