main.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import numpy as np
  2. import networkx as nx
  3. import matplotlib.pyplot as plt
  4. class Lattice():
  5. def __init__(self, n):
  6. self.n = n
  7. self.graph = self._generate_lattice(self.n)
  8. def _generate_lattice(self, n):
  9. lx = range(-n ,n+1, 1)
  10. ly = range(-n ,n+1, 1)
  11. lattice = nx.grid_2d_graph(lx, ly)
  12. return lattice
  13. def generate_configuration(self, p):
  14. nb_edges = len(self.graph.edges())
  15. config = np.random.binomial(1, p, size=nb_edges)
  16. opening = {e: val for e, val in zip(self.graph.edges, config)}
  17. nx.set_edge_attributes(self.graph, values=opening, name='is_open')
  18. return config
  19. def draw(self, config):
  20. _pos = {(x,y):(x,y) for x,y in self.graph.nodes()}
  21. edge_colors = ['white' if d['is_open']==0 else 'black' for (u, v, d) in self.graph.edges(data=True)]
  22. options = {
  23. 'pos': _pos,
  24. 'width':1,
  25. 'edge_color':edge_colors,
  26. 'node_size': .1,
  27. 'node_color': 'black',
  28. # 'linewidth': 0,
  29. }
  30. fig = plt.figure(figsize=(30,30))
  31. nx.draw(
  32. G=self.graph,
  33. **options
  34. )
  35. plt.gca().set_aspect('equal')
  36. # plt.savefig('./figures/my_fig.png',dpi=1000)
  37. plt.show()
  38. if __name__ == "__main__":
  39. lattice = Lattice(50)
  40. latt_conf = lattice.generate_configuration(.2)
  41. lattice.draw(latt_conf)