plot_rcm.py 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. """
  2. ======================
  3. Reverse Cuthill--McKee
  4. ======================
  5. Cuthill-McKee ordering of matrices
  6. The reverse Cuthill--McKee algorithm gives a sparse matrix ordering that
  7. reduces the matrix bandwidth.
  8. """
  9. import numpy as np
  10. import matplotlib.pyplot as plt
  11. import seaborn as sns
  12. import networkx as nx
  13. # build low-bandwidth matrix
  14. G = nx.grid_2d_graph(3, 3)
  15. rcm = list(nx.utils.reverse_cuthill_mckee_ordering(G))
  16. print("ordering", rcm)
  17. print("unordered Laplacian matrix")
  18. A = nx.laplacian_matrix(G)
  19. x, y = np.nonzero(A)
  20. # print(f"lower bandwidth: {(y - x).max()}")
  21. # print(f"upper bandwidth: {(x - y).max()}")
  22. print(f"bandwidth: {(y - x).max() + (x - y).max() + 1}")
  23. print(A)
  24. B = nx.laplacian_matrix(G, nodelist=rcm)
  25. print("low-bandwidth Laplacian matrix")
  26. x, y = np.nonzero(B)
  27. # print(f"lower bandwidth: {(y - x).max()}")
  28. # print(f"upper bandwidth: {(x - y).max()}")
  29. print(f"bandwidth: {(y - x).max() + (x - y).max() + 1}")
  30. print(B)
  31. sns.heatmap(B.todense(), cbar=False, square=True, linewidths=0.5, annot=True)
  32. plt.show()