Beispiel #1
0
 def test_directed(self):
     """Tests for creating a directed triangular lattice."""
     G = nx.triangular_lattice_graph(3, 4, create_using=nx.Graph())
     H = nx.triangular_lattice_graph(3, 4, create_using=nx.DiGraph())
     assert_true(H.is_directed())
     for u, v in H.edges():
         assert_true(v[1] >= u[1])
         if v[1] == u[1]:
             assert_true(v[0] > u[0])
Beispiel #2
0
 def test_directed(self):
     """Tests for creating a directed triangular lattice."""
     G = nx.triangular_lattice_graph(3, 4, create_using=nx.Graph())
     H = nx.triangular_lattice_graph(3, 4, create_using=nx.DiGraph())
     assert H.is_directed()
     for u, v in H.edges():
         assert v[1] >= u[1]
         if v[1] == u[1]:
             assert v[0] > u[0]
Beispiel #3
0
 def test_periodic(self):
     G = nx.triangular_lattice_graph(4, 6, periodic=True)
     assert_equal(len(G), 12)
     assert_equal(G.size(), 36)
     # all degrees are 6
     assert_equal(len([n for n, d in G.degree() if d != 6]), 0)
     G = nx.triangular_lattice_graph(5, 7, periodic=True)
     TLG = nx.triangular_lattice_graph
     assert_raises(nx.NetworkXError, TLG, 2, 4, periodic=True)
     assert_raises(nx.NetworkXError, TLG, 4, 4, periodic=True)
     assert_raises(nx.NetworkXError, TLG, 2, 6, periodic=True)
Beispiel #4
0
 def test_periodic(self):
     G = nx.triangular_lattice_graph(4, 6, periodic=True)
     assert_equal(len(G), 12)
     assert_equal(G.size(), 36)
     # all degrees are 6
     assert_equal(len([n for n, d in G.degree() if d != 6]), 0)
     G = nx.triangular_lattice_graph(5, 7, periodic=True)
     TLG = nx.triangular_lattice_graph
     assert_raises(nx.NetworkXError, TLG, 2, 4, periodic=True)
     assert_raises(nx.NetworkXError, TLG, 4, 4, periodic=True)
     assert_raises(nx.NetworkXError, TLG, 2, 6, periodic=True)
Beispiel #5
0
 def test_periodic(self):
     G = nx.triangular_lattice_graph(4, 6, periodic=True)
     assert len(G) == 12
     assert G.size() == 36
     # all degrees are 6
     assert len([n for n, d in G.degree() if d != 6]) == 0
     G = nx.triangular_lattice_graph(5, 7, periodic=True)
     TLG = nx.triangular_lattice_graph
     pytest.raises(nx.NetworkXError, TLG, 2, 4, periodic=True)
     pytest.raises(nx.NetworkXError, TLG, 4, 4, periodic=True)
     pytest.raises(nx.NetworkXError, TLG, 2, 6, periodic=True)
Beispiel #6
0
def triangular_lattice(m,
                       n,
                       with_boundaries=False,
                       with_lattice_components=False,
                       **kwargs) -> nx.Graph:
    ''' Sanitize networkx properties for Bokeh consumption '''
    if 'periodic' in kwargs:
        kwargs['with_positions'] = False
        G = nx.triangular_lattice_graph(m, n, **kwargs)
        nx.set_node_attributes(G, None, 'contraction')
        return G
    else:
        G = nx.triangular_lattice_graph(m, n, **kwargs)
        if with_lattice_components:
            horiz = nx.Graph()
            for i in range(m + 1):
                sub = G.subgraph([(j, i) for j in range(n)])
                horiz = nx.compose(horiz, sub.copy())
            diag_l = G.copy()
            for i in range(m + 1):
                remove_edges(diag_l, [((j, i), (j + 1, i)) for j in range(n)])
            diag_r = diag_l.copy()
            for i in range(m + 1):
                if i % 2 == 0:
                    remove_edges(diag_l,
                                 [((j, i), (j, i + 1)) for j in range(n)])
                    remove_edges(diag_r,
                                 [((j, i), (j - 1, i + 1)) for j in range(n)])
                else:
                    remove_edges(diag_l,
                                 [((j, i), (j + 1, i + 1)) for j in range(n)])
                    remove_edges(diag_r,
                                 [((j, i), (j, i + 1)) for j in range(n)])
            G.lattice_components = {
                'diag_l': diag_l,
                'diag_r': diag_r,
                'horiz': horiz
            }
        if with_boundaries:
            l = G.subgraph([(0, i) for i in range(m + 1)])
            r_nodes = [(n // 2, 2 * i + 1) for i in range(m // 2 + 1)]
            if n % 2 == 1:
                r_nodes += [(n // 2 + 1, i) for i in range(m + 1)]
            else:
                r_nodes += [(n // 2, 2 * i) for i in range(m // 2 + 1)]
            r = G.subgraph([x for x in r_nodes if x in G.nodes])
            t = G.subgraph([(j, m) for j in range(n)])
            b = G.subgraph([(j, 0) for j in range(n)])
            return G, (l.copy(), r.copy(), t.copy(), b.copy())
        else:
            return G
Beispiel #7
0
def create_graphs(graphtype="grid"):

    if graphtype == "grid":
        graphs = []
        for i in range(4, 6):
            for j in range(4, 6):
                graphs.append(nx.grid_2d_graph(i, j))

    if graphtype == "tri-grid":
        graphs = []
        for i in range(4, 6):
            for j in range(4, 5):
                graphs.append(nx.triangular_lattice_graph(i, j))

    if graphtype == "b-a":
        graphs = []
        for i in range(80, 81):
            for j in range(
                    2, 3
            ):  # j should be lower tahn i ( j = # of edges , i = # of nodes )
                graphs.append(nx.barabasi_albert_graph(i, j))

    if graphtype == "Karate":
        graphs = []
        graphs.append(nx.karate_club_graph())

    return graphs
Beispiel #8
0
def triangular(size, periodic=False):
    """
    Construct a triangular lattice, a lattice whose nodes and edges
    are the triangular tiling of the plane.

    Parameters
    ----------
    size : int, or tuple (m, n) of ints
        size of the lattice (mxn)
    periodic : bool
        Whether boundaries are periodic.

    Returns
    -------
    G : networkx.Graph
        The lattice represented as a networkx.Graph
        The graph has the node attribute 'pos' with the given point
        coordinates, and the edge attribute 'length', which is the
        Euclidean distance between nodes.
    """
    if np.ndim(size) == 0:
        m = size
        n = size
    elif np.ndim(size) == 1:
        m, n = size
    G = nx.triangular_lattice_graph(m, n, periodic=periodic)
    # pos = nx.get_node_attributes(G, 'pos')
    # factor = np.sqrt(2/np.sqrt(3))
    # pos_scaled = {k: factor*np.array(v) for k, v in pos.items()}
    # nx.set_node_attributes(G, pos_scaled, 'pos')
    distances = {(e1, e2): 1 for e1, e2 in G.edges()}
    nx.set_edge_attributes(G, distances, 'length')

    return nx.convert_node_labels_to_integers(G)
Beispiel #9
0
 def __init__(self, xdim=10, ydim=10, grid_type='2d', colorize=True):
     self.xdim = xdim
     self.ydim = ydim
     self.grid_type = grid_type
     if grid_type == '2d':
         self.space = nx.grid_2d_graph(xdim, ydim)
     elif grid_type == 'hex':
         self.space = nx.hexagonal_lattice_graph(xdim, ydim)
     elif grid_type == 'tri':
         self.space = nx.triangular_lattice_graph(xdim, ydim)
     else:
         # TODO: raise exception? default to 2d?
         self.space = nx.grid_2d_graph(xdim, ydim)
     for node in self.space.nodes:
         self.space.node[node]['locale'] = Locale()
     self.conversion_rates = {
         0: 0.2,
         1: 0.1,
         2: 0.15,
         3: 0.05,
         4: 0.1,
         5: 0
     }
     self.time = 0
     self.colorize = colorize
Beispiel #10
0
 def __init__(self, xdim=10, ydim=10, grid_type='2d', flora_system=1, colorize=True, edges=True, slow_burn=False):
     self.xdim = xdim
     self.ydim = ydim
     self.grid_type = grid_type
     if grid_type == '2d':
         self.space = nx.grid_2d_graph(self.xdim, ydim)
     elif grid_type == 'hex':
         self.space = nx.hexagonal_lattice_graph(self.xdim, ydim)
     elif grid_type == 'tri':
         self.space = nx.triangular_lattice_graph(self.xdim, ydim)
     else:
         # TODO: raise exception? default to 2d?
         self.space = nx.grid_2d_graph(self.xdim, ydim)
     for node in self.space.nodes:
         self.space.node[node]['locale'] = Locale(flora_system=flora_system, location=node, region=self)
     self.nodes = set([node for node in self.space.nodes])
     if edges:
         self._add_border_nodes()
     self.conversion_rates = {0: 0.2, 1: 0.1, 2: 0.15, 3: 0.05, 4: 0.1, 5: 0}
     self.time = 0
     self.colorize = colorize
     self.slow_burn = slow_burn
     self.constants = STATE_CONSTANTS
     self.verbose = False
     self.basins_current=False
Beispiel #11
0
def test_is_berge(pool : Pool, alt=False):
    
    if alt:
        from alternate import is_berge_alt as is_berge
    else:
        from berge import is_berge

    # Note that graphs are perfect iff they are Berge

    for i in range(5):
        # Bipartite graphs are always Berge

        n1, n2 = random.randint(1, 12), random.randint(1, 12)
        
        graph = random_bipartite(n1=n1, n2=n2, p=.4)

        assert(is_berge(graph, pool=pool))

    for i in range(5):
        graph = nx.line_graph(random_bipartite(n1=10, n2=10, p=.15))

        # Line graphs of bipartite graphs are perfect by Konig's theorem

        assert(is_berge(graph, pool=pool))

    for i in range(10, 15):
        assert(is_berge(nx.complete_graph(i),  pool=pool))

    for i in range(5):

        # Make sure we work properly on disconnected graphs

        graph = nx.disjoint_union_all([
            random_bipartite(
                random.randint(1, 6), 
                random.randint(1, 6), .2) 
            for i in range(3)])

        assert(is_berge(graph,  pool=pool))

    for i in range(5):
        m = random.randint(2, 12)

        graph = nx.triangular_lattice_graph(m, 2)

        assert(is_berge(graph, pool=pool))

    for i in range(5):
        n = random.randint(4, 20)

        graph = random_chordal(n, .2)

        assert(is_berge(graph, pool=pool))

    for i in range(10):
        n = random.randint(4, 20)

        graph = nx.cycle_graph(n)

        assert(is_berge(graph, pool=pool) == (n % 2 == 0))
Beispiel #12
0
    def set_graph(self, graphtype, graphparams):
        if graphtype == 'hexagonal':
            self.G = nx.triangular_lattice_graph(**graphparams)

        elif graphtype == 'watts strogatz':
            self.G = nx.watts_strogatz_graph(**graphparams)

        elif graphtype == 'newman watts strogatz':
            self.G = nx.newman_watts_strogatz_graph(**graphparams)

        elif graphtype == 'square':
            self.G = nx.grid_2d_graph(**graphparams)

        elif graphtype == 'random blocks':
            self.G = nx.stochastic_block_model(**graphparams)

        elif graphtype == 'powerlaw cluster':
            self.G = nx.powerlaw_cluster_graph(**graphparams)

        elif graphtype == 'scale-free small world':
            self.G = clustered_scalefree(**graphparams)

        elif graphtype == 'barabasi-albert':
            self.G = nx.barabasi_albert_graph(**graphparams)

        else:
            print('Using complete graph')
            self.G = nx.complete_graph(**graphparams)
Beispiel #13
0
def generate_graph(m, n):
    G = nx.triangular_lattice_graph(m, n)
    A = nx.to_numpy_matrix(G)
    G = nx.from_numpy_matrix(A)
    data = json_graph.node_link_data(G)
    with open('./Working/graph.json', 'w') as f:
        json.dump(data, f)
    with open('./Working/graph_flag', mode='w', encoding='utf-8') as fh:
        fh.write("i look at you")
    def __init__(self, network_type, size, **kwargs):

        if network_type == '2D_lattice': 
            tiling = kwargs['tiling']
            per = kwargs['periodic']
            if tiling == 3: 
                self.graph = nx.triangular_lattice_graph(size, size, periodic = per, with_positions = True)
                self.pos = nx.get_node_attributes(self.graph,'pos')
                self.M = len(self.graph.edges())
                self.N = len(self.graph.nodes())
                

            elif tiling == 4: 
                self.graph = nx.grid_2d_graph(size, size, periodic = per)
                self.pos = dict( (n, n) for n in self.graph.nodes() )
                self.labels = dict( ((i, j), i * size + j) for i, j in self.graph.nodes() )
                self.M = len(self.graph.edges())
                self.N = len(self.graph.nodes())
                
            elif tiling == 6: 
                self.graph = nx.hexagonal_lattice_graph(size, size, periodic = per, with_positions = True)
                self.pos = nx.get_node_attributes(self.graph,'pos')
                self.M = len(self.graph.edges())
                self.N = len(self.graph.nodes())
            
            
        elif network_type == 'ring_lattice':# TODO: banding for every node
            self.graph = nx.cycle_graph(size)
            theta = (2*np.pi)/size
            self.pos = dict((i,(np.sin(theta*i),np.cos(theta*i))) for i in range(size))
            self.M = len(self.graph.edges())
            self.N = len(self.graph.nodes())
            self.text = 'Ring Lattice'
            if kwargs['banded']:
                if kwargs['band_length'] >= int(self.N/2)-1: 
                    raise ValueError('Band length cannot exceed the half of the size of the network')
                if kwargs['band_length'] <2: 
                    raise ValueError('Band length should be a positive integer greater 1 since the closest neighbors are already connected')
                for u in range(self.N):
                    for i in range(2,kwargs['band_length']+1):
                        # ranges from 2 to k+2 to avoid the closest node and start
                        ## banding from the second closest node
                        if u + i >= self.N: v = u + i - self.N
                        else: v = u + i
                        self.graph.add_edge(u, v)
                        if u - i < 0: v = self.N + u - i
                        else: v = u - i
                        self.graph.add_edge(u, v)
                self.text = self.text + ' w/ bandlength %d'%kwargs['band_length']
            else:self.text = self.text + ' w/ bandlength 0'
                        
        else: raise ValueError('network type can be a lattice or a ring')
            
        self.A = nx.adjacency_matrix(self.graph)
def triangular_lattice(m, n, periodic, directed, weighted):

    #Generate Network:
    triangular_lattice = nx.triangular_lattice_graph(m, n, periodic=periodic)

    #Give the nodes an initial position:
    node_position = position_nodes(triangular_lattice)

    #If the network is weighted, add edge weights:
    #if weighted:
    #    weight_edges(triangular_lattice)

    return triangular_lattice, node_position
def Create_Minimum_Data(n, num):

    k = 0.5

    if num == 1:
        G = nx.grid_2d_graph(n, n)
    if num == 2:
        G = nx.triangular_lattice_graph(n, n)
    if num == 3:
        G = nx.path_graph(n)
    if num == 4:
        G = Create_Triangular_Graph(n)
    if num == 5:
        G = Create_Kagome_Graph(n, n, plot=False)

    N = len(G.nodes())

    m = int(round(k * N))
    n = int(round((1 - k) * N))

    a = np.ones(N)
    a[:m] = -1
    np.random.shuffle(a)

    node_colors = []
    for i in a:
        if i == 1:
            node_colors.append("Silver")
        else:
            node_colors.append("Black")

    attr = {}
    for (node, value), color in zip(G.nodes.data(), node_colors):
        attr[node] = color

    nx.set_node_attributes(G, attr, 'color')

    G = Add_Weights(G, 1.0)

    matrix = nx.to_numpy_matrix(G)
    g, weights, signed_matrix = Prepare_Data([matrix])

    fi, vr = Optimization_Model(weights, signed_matrix)
    #frustrations.append(fi)
    G = color_nodes(G, vr)

    #pos = nx.spring_layout(G, weight=None)
    #nx.set_node_attributes(G,pos,'pos')

    return G
Beispiel #17
0
 def test_lattice_points(self):
     """Tests that the graph is really a triangular lattice."""
     for m, n in [(2, 3), (2, 2), (2, 1), (3, 3), (3, 2), (3, 4)]:
         G = nx.triangular_lattice_graph(m, n)
         N = (n + 1) // 2
         assert_equal(len(G), (m + 1) * (1 + N) - (n % 2) * ((m + 1) // 2))
     for (i, j) in G.nodes():
         nbrs = G[(i, j)]
         if i < N:
             assert_true((i + 1, j) in nbrs)
         if j < m:
             assert_true((i, j + 1) in nbrs)
         if j < m and (i > 0 or j % 2) and (i < N or (j + 1) % 2):
             assert_true((i + 1, j + 1) in nbrs or (i - 1, j + 1) in nbrs)
Beispiel #18
0
 def test_lattice_points(self):
     """Tests that the graph is really a triangular lattice."""
     for m, n in [(2, 3), (2, 2), (2, 1), (3, 3), (3, 2), (3, 4)]:
         G = nx.triangular_lattice_graph(m, n)
         N = (n + 1) // 2
         assert len(G) == (m + 1) * (1 + N) - (n % 2) * ((m + 1) // 2)
     for (i, j) in G.nodes():
         nbrs = G[(i, j)]
         if i < N:
             assert (i + 1, j) in nbrs
         if j < m:
             assert (i, j + 1) in nbrs
         if j < m and (i > 0 or j % 2) and (i < N or (j + 1) % 2):
             assert (i + 1, j + 1) in nbrs or (i - 1, j + 1) in nbrs
Beispiel #19
0
def generate_graph(m, n):
    G = nx.triangular_lattice_graph(m, n)
    A = nx.to_numpy_matrix(G)
    G = nx.from_numpy_matrix(A)
    node_data = []
    for i in nx.nodes(G):
        node_data.append(i)
    node_data = pd.DataFrame(node_data)
    node_data.to_csv("./Resources/Output/Working/node.csv")
    print('[Python]' + 'Generate Node')
    edge_data = nx.to_pandas_edgelist(G)
    edge_data.to_csv("./Resources/Output/Working/edge.csv")
    print('[Python]' + 'Generate Edge')
    with open('./Resources/Output/Working/flag', mode='w',
              encoding='utf-8') as fh:
        fh.write("i look at you")
def Create_Random_Data(n, choice, k=False):

    if choice == 1:
        G = nx.grid_2d_graph(n, n)
    if choice == 2:
        G = nx.triangular_lattice_graph(n, n)
    if choice == 3:
        G = nx.path_graph(n)
    if choice == 4:
        G = Create_Triangular_Graph(n)
    if choice == 5:
        G = Create_Kagome_Graph(n, n, plot=False)

    N = len(G.nodes())

    if type(k) == bool:
        m = random.randrange(0, N)
        n = N - m
    else:
        m = int(round(k * N))
        n = int(round((1 - k) * N))

    a = np.ones(N)
    a[:m] = -1
    np.random.shuffle(a)

    node_colors = []
    for i in a:
        if i == 1:
            node_colors.append("Silver")
        else:
            node_colors.append("Black")

    attr = {}
    for (node, value), color in zip(G.nodes.data(), node_colors):
        attr[node] = color

    nx.set_node_attributes(G, attr, 'color')

    G = Add_Weights(G, 1.0)

    #pos = nx.spring_layout(G, weight=None)
    #nx.set_node_attributes(G,pos,'pos')

    return G
Beispiel #21
0
def create_graph(type, width, height):
    if type == SQUARE:
        graph = nx.grid_2d_graph(width, height)
        faces = create_square_faces(width, height)
    elif type == TRIANGLE_LEFT:
        graph = nx.triangular_lattice_graph(width, height, with_positions=True)
        faces = []
    else:
        raise ValueError("No valid graph type passed.")

    set_node_attributes(graph,
                        {n: {
                            "cx": n[0],
                            "cy": n[1]
                        }
                         for n in graph.nodes})

    return graph, faces
Beispiel #22
0
def triangular_cylinder(m, n) -> nx.Graph:
    '''
	Y-periodic triangular lattice
	'''
    G = nx.triangular_lattice_graph(m, n)
    N = (n + 1) // 2  # number of nodes in row
    cols = range(N + 1)
    for i in cols:
        G = nx.contracted_nodes(G, (i, 0), (i, m))
    nx.set_node_attributes(G, None, 'contraction')
    G.l_boundary = G.subgraph([(0, i) for i in range(m)])
    r_nodes = [(n // 2, 2 * i + 1) for i in range(m // 2 + 1)]
    if n % 2 == 1:
        r_nodes += [(n // 2 + 1, i) for i in range(m + 1)]
    else:
        r_nodes += [(n // 2, 2 * i) for i in range(m // 2 + 1)]
    G.r_boundary = G.subgraph([x for x in r_nodes if x in G.nodes])
    G.faces = find_k_cliques(G, 3)
    return G
Beispiel #23
0
def getGraphData(u, v, k):
    center, space = _center(k), _space(k)
    actual, dis = {}, {}
    G = nx.triangular_lattice_graph(space, space, periodic=False,
                                    with_positions=True,
                                    create_using=None)
    pos = nx.get_node_attributes(G, 'pos')

    # node locations and distances from 0,0
    for n in G.nodes:
        x = n[0] - center - v[0]
        x2 = n[0] - center
        x = round(float(np.dot(x if (n[1] % 2 == 0) else x2, u[0])), DP)
        y = round(float(np.dot(n[1] - center, v[1])), DP)
        actual[n] = (x, y)
        dis[n] = np.sqrt(np.power(actual[n][0], SQ) + np.power(actual[n][1], SQ))
    dis = dict(sorted(dis.items(), key=lambda item: item[1]))
    dis_items = list(dis.items())
    firstK = dis_items[:k]
    var = {d: G.remove_node(d[0]) for d in dis_items[k:]}
    firstK = [round(column[1], 2) for column in firstK]

    return G, pos, actual, firstK
Beispiel #24
0
def triangular_lattice_graph(m, n):
    G = nx.triangular_lattice_graph(m, n, with_positions=True)
    F = nx.Graph(name='triangular')
    F.add_edges_from(G.edges)
    F.graph['pos'] = nx.get_node_attributes(G, 'pos')
    return F
Beispiel #25
0
 def test_multigraph(self):
     """Tests for creating a triangular lattice multigraph."""
     G = nx.triangular_lattice_graph(3, 4, create_using=nx.Graph())
     H = nx.triangular_lattice_graph(3, 4, create_using=nx.MultiGraph())
     assert list(H.edges()) == list(G.edges())
Beispiel #26
0
import matplotlib.pyplot as plt

import networkx as nx

# Decentralized graphs
G = nx.random_lobster(0.8, 0.9, 0.8, seed=5)

# Centralized graphs
G2 = nx.Graph()
G2.add_nodes_from(G.nodes())

center = 0
for node in G2.nodes():
    if node != center:
        G2.add_edge(center, node)

# Distributed graph
G3 = nx.triangular_lattice_graph(10, 20, with_positions=True)
pos = nx.get_node_attributes(G3, 'pos')

# Uncomment to draw graph
# nx.draw(G, node_size=90, linewidths=.8)
# nx.draw(G2, node_size=90, linewidths=.8)
nx.draw_kamada_kawai(G3, node_size=90, linewidths=.8)
plt.show()
Beispiel #27
0
plt.xticks([])
plt.yticks([])

#m×n的六角形格子图。
G = nx.hexagonal_lattice_graph(3, 3)
plt.subplot(2, 3, 3)
nx.draw(G, with_labels=True)
plt.title('hexagonal_lattice_graph')
plt.axis('on')
plt.xticks([])
plt.yticks([])

#n维超立方体图形。
G = nx.hypercube_graph(3)
plt.subplot(2, 3, 4)
nx.draw(G, with_labels=True)
plt.title('hypercube_graph')
plt.axis('on')
plt.xticks([])
plt.yticks([])

#三角格子图
G = nx.triangular_lattice_graph(11, 3)
plt.subplot(2, 3, 5)
nx.draw(G, with_labels=True)
plt.title('hypercube_graph')
plt.axis('on')
plt.xticks([])
plt.yticks([])

plt.show()
Beispiel #28
0
 def test_multigraph(self):
     """Tests for creating a triangular lattice multigraph."""
     G = nx.triangular_lattice_graph(3, 4, create_using=nx.Graph())
     H = nx.triangular_lattice_graph(3, 4, create_using=nx.MultiGraph())
     assert_equal(list(H.edges()), list(G.edges()))
def triangular(m, n, periodic=False, dist_function=None):
    G = nx.triangular_lattice_graph(m, n, periodic=periodic)
    return G
    bound = 1
    if partition.parent is not None:
        bound = (partition["base"]**(-len(partition["cut_edges"]) +
                                     len(partition.parent["cut_edges"]))
                 )  #*(len(boundaries1)/len(boundaries2))

    return random.random() < bound


for pop1 in pops:
    for base in bases:
        for alignment in [2, 1, 0]:

            m = 50
            G = nx.grid_graph([m, m])
            H = nx.triangular_lattice_graph(m, 2 * m - 2)
            relabel = {}
            for x in G.nodes():
                relabel[x] = (x[0], x[1] - m + 1)
            G = nx.relabel_nodes(G, relabel)

            ####Here is the FRANK2engraph
            F = nx.compose(G, H)
            '''
            for i in range(-m,m):
                value = 0
                for x in F.nodes():
                    if x[1] == i:
                        value += 1
                print(i,value)
            '''
Beispiel #31
0
class TestSpatialGraph(unittest.TestCase):
    """Tests for the feems SpatialGraph
    """
    # generate a simple networkx graph with 4 nodes and 4 samples observed on
    # only 2 of the 4 nodes
    graph = nx.triangular_lattice_graph(1, 2, with_positions=True)
    graph = nx.convert_node_labels_to_integers(graph)
    pos = nx.get_node_attributes(graph, "pos")
    node_pos = np.array(list(pos.values()))
    sample_pos = np.empty((4, 2))
    sample_pos[0, :] = node_pos[0, ]
    sample_pos[1, :] = node_pos[0, ]
    sample_pos[2, :] = node_pos[2, ]
    sample_pos[3, :] = node_pos[2, ]
    edges = np.array(list(graph.edges)) + 1
    n_snps = 100
    genotypes = np.random.binomial(n=2,
                                   p=.5,
                                   size=(sample_pos.shape[0], n_snps))

    # setup the spatial graph
    sp_graph = SpatialGraph(genotypes, sample_pos, node_pos, edges)

    def test_idx(self):
        """Tests original node indicies
        """
        idx = query_node_attributes(self.sp_graph, "idx")
        self.assertEqual(idx.tolist(), [0, 1, 2, 3])

    def test_node_pos(self):
        """Tests for the correct node positions
        """
        pos = query_node_attributes(self.sp_graph, "pos")
        self.assertEqual(pos.tolist(), self.node_pos.tolist())

    def test_sample_idx(self):
        """Tests assignment of samples to nodes
        """
        sample_idx_dict = nx.get_node_attributes(self.sp_graph, "sample_idx")
        self.assertEqual(sample_idx_dict[0], [0, 1])
        self.assertEqual(sample_idx_dict[1], [])
        self.assertEqual(sample_idx_dict[2], [2, 3])
        self.assertEqual(sample_idx_dict[3], [])

    def test_permuted_idx(self):
        """Tests permutation of nodes
        """
        permuted_idx = query_node_attributes(self.sp_graph, "permuted_idx")
        self.assertEqual(permuted_idx.tolist(), [0, 2, 1, 3])

    def test_n_samples_per_obs_node_permuted(self):
        """Tests permutation of n samples
        """
        ns = self.sp_graph.n_samples_per_obs_node_permuted
        self.assertEqual(ns.tolist(), [2, 2])

    def test_n_observed_nodes(self):
        """Tests the right number of observed nodes
        """
        self.assertEqual(self.sp_graph.n_observed_nodes, 2)

    def test_estimate_allele_frequencies(self):
        """Tests allele frequency estimation on the observed nodes of the
        graph
        """
        node_0_freqs = np.mean(self.genotypes[[0, 1], :], axis=0)  # / 4.0
        node_2_freqs = np.mean(self.genotypes[[2, 3], :], axis=0)  # / 4.0
        exp_freqs = np.vstack([node_0_freqs, node_2_freqs])
        self.assertEqual(self.sp_graph.frequencies.tolist(),
                         exp_freqs.tolist())
Beispiel #32
0
__author__ = 'fhca'

import networkx as nx
import matplotlib.pyplot as plt
import matplotlib

matplotlib.use('TkAgg')

G = nx.triangular_lattice_graph(20, 20)
plt.figure(figsize=(8, 8))
pos = nx.spring_layout(G, iterations=200)
nx.draw_networkx_nodes(G, pos, node_size=1)
nx.draw_networkx_edges(G, pos, alpha=.5)

plt.show()
"""
from networkx.drawing.nx_pydot import write_dot
G = nx.triangular_lattice_graph(20,20)
pos = nx.nx_agraph.graphviz_layout(G)
nx.draw(G, pos=pos)
write_dot(G, 'file.gv')
"""
def generate_graph(parameters, type='random'):

    #n, type='random', d=0, m=0, k=5, p=.5, periodic=False, with_positions=True, create_using=None
    '''

    INPUTS: 
    
    type              Type of graph
    parameters        List of parameters specific to the type of graph

    OUTPUTS:
    Graph satisfying the specified parameters and of the specified type
  '''
    try:
        if type == 'triangular_lattice':
            n_dim = parameters[0]
            m_dim = parameters[1]
            graph = nx.triangular_lattice_graph(n_dim, m_dim)
            return graph

        if type == 'hypercube':
            num_nodes = parameters[0]
            graph = nx.hypercube_graph(num_nodes)
            return graph

        elif type == 'random':
            num_nodes = parameters[0]
            av_deg = parameters[1]
            graph = nx.random_regular_graph(av_deg, num_nodes)
            return graph

        elif type == 'erdos_renyi':
            num_nodes = parameters[0]
            edges = parameters[1]
            graph = nx.erdos_renyi_graph(num_nodes, edges)

        elif type == 'complete':
            num_nodes = parameters[0]
            graph = nx.complete_graph(num_nodes)

        elif type == 'dumbell':
            n = parameters[0]
            graph = nx.barbell_graph(n // 2 - 1, n - 2 * (n // 2 - 1))

        elif type == 'complete_bipartite':
            m = parameters[0]
            n = parameters[1]
            graph = nx.complete_bipartite_graph(m, n)

        elif type == 'dumbell_multiple':
            size_dumbell = parameters[0]
            num_dumbell = parameters[1]
            size_path = parameters[2]
            graph = generate_dumbell_multiple_cliques(size_dumbell,
                                                      num_dumbell, size_path)

        elif type == 'rich_club':
            size_club = parameters[0]
            size_periphery = parameters[1]
            #prob_rp = parameters[2]
            #prob_rr = parameters[3]
            #prob_pp = parameters[4]
            num_peripheries = parameters[2]
            a = parameters[3]
            b = parameters[4]
            c = parameters[5]
            graph = generate_rich_club_adapted_version(size_club,
                                                       size_periphery,
                                                       num_peripheries, a, b,
                                                       c)

        elif type == 'dumbell_multiple_sized':
            size_list = parameters[0]
            path_length = parameters[1]
            graph = generate_dumbell_multiple_sizes(size_list, path_length)

        elif type == 'dumbell_string':
            sizes = parameters[0]
            lengths = parameters[1]
            graph = generate_dumbell_string(sizes, lengths)

        elif type == 'with_indicator':
            indicator = parameters[0]
            graph = generate_dumbell_indicator_connectionstrength(indicator)

        return graph

    except ValueError:
        print("The specified graph type was invalid.")