Advertisement
Guest User

Untitled

a guest
Apr 20th, 2019
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.09 KB | None | 0 0
  1. #!/usr/bin/env python
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4.  
  5.  
  6. def vectors_uniform(k):
  7. """Uniformly generates k vectors."""
  8. vectors = []
  9. for a in np.linspace(0, 2 * np.pi, k, endpoint=False):
  10. vectors.append(2 * np.array([np.sin(a), np.cos(a)]))
  11. return vectors
  12.  
  13.  
  14. def visualize_transformation(A, vectors):
  15. """Plots original and transformed vectors for a given 2x2 transformation matrix A and a list of 2D vectors."""
  16. for i, v in enumerate(vectors):
  17. # Plot original vector.
  18. plt.quiver(0.0, 0.0, v[0], v[1], width=0.008, color="blue", scale_units='xy', angles='xy', scale=1,
  19. zorder=4)
  20. plt.text(v[0]/2 + 0.25, v[1]/2, "v{0}".format(i), color="blue")
  21.  
  22. # Plot transformed vector.
  23. tv = A.dot(v)
  24. plt.quiver(0.0, 0.0, tv[0], tv[1], width=0.005, color="magenta", scale_units='xy', angles='xy', scale=1,
  25. zorder=4)
  26. plt.text(tv[0] / 2 + 0.25, tv[1] / 2, "v{0}'".format(i), color="magenta")
  27. plt.xlim([-6, 6])
  28. plt.ylim([-6, 6])
  29. plt.margins(0.05)
  30. # Plot eigenvectors
  31. plot_eigenvectors(A)
  32. plt.show()
  33.  
  34.  
  35. def visualize_vectors(vectors, color="green"):
  36. """Plots all vectors in the list."""
  37. for i, v in enumerate(vectors):
  38. plt.quiver(0.0, 0.0, v[0], v[1], width=0.006, color=color, scale_units='xy', angles='xy', scale=1,
  39. zorder=4)
  40. plt.text(v[0] / 2 + 0.25, v[1] / 2, "eigv{0}".format(i), color=color)
  41.  
  42.  
  43. def plot_eigenvectors(A):
  44. """Plots all eigenvectors of the given 2x2 matrix A."""
  45. # TODO: Zad. 4.1. Oblicz wektory własne A. Możesz wykorzystać funkcję np.linalg.eig
  46. # eigvec = []
  47. (eigvalues, eigvec) = np.linalg.eig(A)
  48. # TODO: Zad. 4.1. Upewnij się poprzez analizę wykresów, że rysowane są poprawne wektory własne (łatwo tu o pomyłkę).
  49. visualize_vectors(eigvec.T)
  50.  
  51.  
  52. def EVD_decomposition(A):
  53. # TODO: Zad. 4.2. Uzupełnij funkcję tak by obliczała rozkład EVD zgodnie z zadaniem.
  54. (eigvalues, K) = np.linalg.eig(A)
  55. K_inv = np.linalg.inv(K)
  56. L = np.dot(np.dot(K_inv, A), K)
  57.  
  58. print("Eigvalues")
  59. print(eigvalues)
  60. print("K")
  61. print(K)
  62. print("L")
  63. print(L)
  64.  
  65. print("A")
  66. print(A)
  67. print("KLK^-1")
  68. print(np.dot(np.dot(K, L), K_inv))
  69.  
  70. def calculate_vector_length(vector):
  71. result = 0
  72. for v in vector:
  73. result += v**2
  74. return np.sqrt(result)
  75.  
  76.  
  77. def plot_attractors(A):
  78.  
  79. vectors = vectors_uniform(k=20)
  80.  
  81. (eigvalues, K) = np.linalg.eig(A)
  82.  
  83. normalized_eigen_vectors = []
  84.  
  85. for k in K.T:
  86. k_length = calculate_vector_length(k)
  87. normalized_eigen_vectors.append(k/k_length)
  88. normalized_eigen_vectors.append(-k/k_length)
  89.  
  90.  
  91. colors = []
  92. for i in range(int(len(normalized_eigen_vectors)/2)):
  93. colors.append(((0.1/(i+0.1))**2, (i-(i/(1+i)))/(i+1), (0.5/(i+0.5)), 0.8))
  94. colors.append((1-(1/(i+1))**2, (i/(1+i)), 1-(1/(i+1)), 0.4))
  95.  
  96. for i, eigen_vectors in enumerate(normalized_eigen_vectors):
  97. plt.quiver(0.0, 0.0, eigen_vectors[0], eigen_vectors[1], width=0.02, color=colors[i], scale_units='xy', angles='xy', scale=1,
  98. zorder=4)
  99.  
  100. # TODO: Zad. 4.3. Uzupełnij funkcję tak by generowała wykres z atraktorami.
  101. for i, v in enumerate(vectors):
  102. # Plot original vector.
  103. new_v = v/calculate_vector_length(v)
  104. for _ in range(10):
  105. new_v = np.dot(A, new_v)
  106. new_v = new_v/calculate_vector_length(new_v)
  107.  
  108. min_distance = float("inf")
  109. min_index = None
  110. for index, normalized_eigen_vector in enumerate(normalized_eigen_vectors):
  111. dist = np.linalg.norm(new_v - normalized_eigen_vector)
  112. if dist < min_distance:
  113. min_distance = dist
  114. min_index = index
  115.  
  116. v /= calculate_vector_length(v)
  117. # plt.quiver(0.0, 0.0, new_v[0], new_v[1], width=0.008, color="yellow", scale_units='xy', angles='xy', scale=1,
  118. # zorder=4)
  119.  
  120. plt.quiver(0.0, 0.0, v[0], v[1], width=0.008, color=colors[min_index], scale_units='xy', angles='xy', scale=1,
  121. zorder=4)
  122. # plt.text(v[0] / 2 + 0.25, v[1] / 2, "v{0}".format(i), color="blue")
  123. plt.xlim([-1.1, 1.1])
  124. plt.ylim([-1.1, 1.1])
  125. plt.margins(0.05)
  126. plt.show()
  127.  
  128.  
  129. def test_A1(vectors):
  130. """Standard scaling transformation."""
  131. A = np.array([[2, 0],
  132. [0, 2]])
  133. EVD_decomposition(A)
  134. visualize_transformation(A, vectors)
  135. plot_attractors(A)
  136.  
  137.  
  138. def test_A2(vectors):
  139. A = np.array([[-1, 2],
  140. [2, 1]])
  141. EVD_decomposition(A)
  142. visualize_transformation(A, vectors)
  143. plot_attractors(A)
  144.  
  145.  
  146. def test_A3(vectors):
  147. A = np.array([[3, 1],
  148. [0, 2]])
  149. EVD_decomposition(A)
  150. visualize_transformation(A, vectors)
  151. plot_attractors(A)
  152.  
  153.  
  154.  
  155. if __name__ == "__main__":
  156. vectors = vectors_uniform(k=8)
  157.  
  158.  
  159. test_A1(vectors)
  160. test_A2(vectors)
  161. test_A3(vectors)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement