def grid_graph(dim,periodic=False,create_using=None): """ Return the n-dimensional grid graph. The dimension is the length of the list 'dim' and the size in each dimension is the value of the list element. E.g. G=grid_graph(dim=[2,3]) produces a 2x3 grid graph. If periodic=True then join grid edges with periodic boundary conditions. """ from networkx.utils import is_list_of_ints if create_using is not None and create_using.is_directed(): raise networkx.NetworkXError("Directed Graph not supported") dlabel="%s"%dim if dim==[]: G=empty_graph(0,create_using) G.name="grid_graph(%s)"%dim return G if not is_list_of_ints(dim): raise networkx.NetworkXError("dim is not a list of integers") if min(dim)<=0: raise networkx.NetworkXError(\ "dim is not a list of strictly positive integers") if periodic: func=cycle_graph else: func=path_graph current_dim=dim.pop() G=func(current_dim,create_using) while len(dim)>0: current_dim=dim.pop() # order matters: copy before it is cleared during the creation of Gnew Gold=G.copy() Gnew=func(current_dim,create_using) # explicit: create_using=None # This is so that we get a new graph of Gnew's class. G=networkx.operators.cartesian_product(Gnew,Gold,create_using=None) # graph G is done but has labels of the form (1,(2,(3,1))) # so relabel H=networkx.operators.relabel_nodes(G, networkx.utils.flatten) H.name="grid_graph(%s)"%dlabel return H
def grid_graph(dim,periodic=False): """ Return the n-dimensional grid graph. The dimension is the length of the list 'dim' and the size in each dimension is the value of the list element. E.g. G=grid_graph(dim=[2,3]) produces a 2x3 grid graph. If periodic=True then join grid edges with periodic boundary conditions. """ from networkx.utils import is_list_of_ints dlabel="%s"%dim if dim==[]: G=networkx.Graph() G.name="grid_graph(%s)"%dim return G if not is_list_of_ints(dim): raise networkx.NetworkXError,"dim is not a list of integers" if min(dim)<=0: raise networkx.NetworkXError,\ "dim is not a list of strictly positive integers" if periodic: func=cycle_graph else: func=path_graph current_dim=dim.pop() G=func(current_dim) while len(dim)>0: current_dim=dim.pop() Gnew=func(current_dim) Gold=G.copy() G=networkx.operators.cartesian_product(Gnew,Gold) # graph G is done but has labels of the form (1,(2,(3,1))) # so relabel H=networkx.operators.relabel_nodes(G, networkx.utils.flatten) H.name="grid_graph(%s)"%dlabel return H