Beispiel #1
0
def test_structure():
    # with a structure
    room1 = nngt.Group(25)
    room2 = nngt.Group(50)
    room3 = nngt.Group(40)
    room4 = nngt.Group(35)

    names = ["R1", "R2", "R3", "R4"]

    struct = nngt.Structure.from_groups((room1, room2, room3, room4), names)

    g = nngt.Graph(structure=struct)

    for fmt in formats:
        g.to_file(gfilename, fmt=fmt)

        h = nngt.load_from_file(gfilename, fmt=fmt)

        assert g.structure == h.structure

    # with a neuronal population
    g = nngt.Network.exc_and_inhib(100)

    for fmt in formats:
        g.to_file(gfilename, fmt=fmt)

        h = nngt.load_from_file(gfilename, fmt=fmt)

        assert g.population == h.population
Beispiel #2
0
def test_hive_plot():
    g = nngt.load_from_file(dirpath + "/Networks/rat_brain.graphml",
                            attributes=["weight"],
                            cleanup=True,
                            attributes_types={"weight": float})

    cc = nngt.analysis.local_clustering(g, weights="weight")

    g.new_node_attribute("cc", "double", values=cc)

    g.new_node_attribute("strength",
                         "double",
                         values=g.get_degrees(weights="weight"))

    g.new_node_attribute("SC",
                         "double",
                         values=nngt.analysis.subgraph_centrality(g))

    cc_bins = [0, 0.1, 0.25, 0.6]

    nplt.hive_plot(g, g.get_degrees(), axes="cc", axes_bins=cc_bins)

    nplt.hive_plot(g,
                   "strength",
                   axes="cc",
                   axes_bins=cc_bins,
                   axes_units="rank")

    # set colormap and highlight nodes
    nodes = list(range(g.node_nb(), 3))

    nplt.hive_plot(g,
                   "strength",
                   axes="SC",
                   axes_bins=4,
                   axes_colors="brg",
                   highlight_nodes=nodes)

    # multiple radial axes and edge highlight
    rad_axes = ["cc", "strength", "SC"]
    edges = g.get_edges(source_node=nodes)

    nplt.hive_plot(g,
                   rad_axes,
                   rad_axes,
                   nsize=g.get_degrees(),
                   max_nsize=50,
                   highlight_edges=edges)

    # check errors
    with pytest.raises(ValueError):
        nplt.hive_plot(g, [cc, "closeness", "strength"])
        nplt.hive_plot(g, 124)

    with pytest.raises(AssertionError):
        nplt.hive_plot(g, cc, axes=[1, 2, 3])
        nplt.hive_plot(g, cc, axes=1)
        nplt.hive_plot(g, cc, axes="groups")
Beispiel #3
0
def test_empty_out_degree():
    g = nngt.Graph(2)

    g.new_edge(0, 1)

    for fmt in formats:
        nngt.save_to_file(g, gfilename, fmt=fmt)

        h = nngt.load_from_file(gfilename, fmt=fmt)

        assert np.array_equal(g.edges_array, h.edges_array)
Beispiel #4
0
def test_str_attr():
    ''' Check string attributes '''
    g = nngt.Graph(5)

    # set node attribute
    node_names = ["aa", "b", "c", "dddd", "eee"]

    g.new_node_attribute("name", "string", values=node_names)

    # set edges
    edges = [(0, 1), (1, 3), (1, 4), (2, 0), (3, 2), (4, 1)]

    g.new_edges(edges)

    # set edge attribute
    eattr = ["a" * i for i in range(len(edges))]

    g.new_edge_attribute("edata", "string", values=eattr)

    # check attributes
    assert list(g.node_attributes["name"]) == node_names
    assert list(g.edge_attributes["edata"]) == eattr

    # save and load string attributes
    current_dir = os.path.dirname(os.path.abspath(__file__)) + '/'

    filename = current_dir + "g.el"

    g.to_file(filename)

    h = nngt.load_from_file(filename)

    assert list(h.node_attributes["name"]) == node_names
    assert list(h.edge_attributes["edata"]) == eattr

    os.remove(filename)

    # change an attribute
    node_names[2] = "cc"
    h.set_node_attribute("name", values=node_names)

    assert not np.array_equal(h.node_attributes["name"],
                              g.node_attributes["name"])

    assert list(h.node_attributes["name"]) == node_names

    eattr[0] = "l"
    h.set_edge_attribute("edata", values=eattr)

    assert not np.array_equal(h.edge_attributes["edata"],
                              g.edge_attributes["edata"])

    assert list(h.edge_attributes["edata"]) == eattr
Beispiel #5
0
def test_node_attributes():
    num_nodes = 10
    g = nngt.generation.erdos_renyi(nodes=num_nodes, avg_deg=3, directed=False)

    g.new_node_attribute("size", "int",
                         [2 * (i + 1) for i in range(num_nodes)])

    for fmt in formats:
        g.to_file(gfilename, fmt=fmt)

        h = nngt.load_from_file(gfilename, fmt=fmt)

        assert np.array_equal(g.node_attributes["size"],
                              h.node_attributes["size"])
Beispiel #6
0
    def load_network(self, filename, **kwargs):
        '''
        Load a network from a file.

        See
        ---
        :func:`nngt.load_from_file`
        '''
        self._network = nngt.load_from_file(filename, **kwargs)
        delays = self._network.get_delays()
        d0 = delays[0]
        for d in delays:
            if d != d0:
                self._network = None
                raise ValueError("Invalid network: all delays must be equal.")
Beispiel #7
0
def test_partial_graphml():
    '''
    Check that the GraphML file loads fine if some attributes are missing.
    '''
    g = nngt.load_from_file(
        os.path.join(current_dir, "Networks/missing_attrs.graphml"))

    nattrs = {0: "A", 1: "", 2: "C", 3: "D"}
    eattrs = {(0, 1): 4, (0, 2): 1, (2, 3): np.NaN, (3, 1): 0.5}

    for n, name in nattrs.items():
        assert g.node_attributes["name"][n] == name

    for e, value in eattrs.items():
        if np.isnan(value):
            assert np.isnan(g.get_edge_attributes(edges=e, name="eattr"))
        else:
            assert g.get_edge_attributes(edges=e, name="eattr") == value
Beispiel #8
0
def test_spatial():
    from nngt.geometry import Shape

    shape = Shape.disk(100, default_properties={"plop": 0.2, "height": 1.})
    area = Shape.rectangle(10, 10, default_properties={"height": 10.})
    shape.add_area(area, name="center")

    g = nngt.SpatialGraph(20, shape=shape)

    for fmt in formats:
        g.to_file(gfilename, fmt=fmt)

        h = nngt.load_from_file(gfilename, fmt=fmt)

        assert np.all(np.isclose(g.get_positions(), h.get_positions()))
        assert g.shape.normalize().almost_equals(h.shape.normalize(), 1e-5)

        for name, area in g.shape.areas.items():
            assert area.normalize().almost_equals(
                h.shape.areas[name].normalize(), 1e-5)

            assert area.properties == h.shape.areas[name].properties
Beispiel #9
0
def test_str_attributes():
    g = nngt.Graph(2)

    g.new_edge(0, 1)

    g.new_edge_attribute("type", "string")
    g.set_edge_attribute("type", val='odd')

    g.new_node_attribute("rnd", "string")
    g.set_node_attribute("rnd", values=["s'adf", 'sd fr"'])

    for fmt in formats:
        nngt.save_to_file(g, gfilename, fmt=fmt)

        h = nngt.load_from_file(gfilename, fmt=fmt)

        assert np.array_equal(g.edges_array, h.edges_array)

        assert np.array_equal(g.edge_attributes["type"],
                              h.edge_attributes["type"])

        assert np.array_equal(g.node_attributes["rnd"],
                              h.node_attributes["rnd"])
Beispiel #10
0
import inspect
from os.path import abspath, dirname

import matplotlib.pyplot as plt

import nngt

plt.rcParams.update({"figure.facecolor": (0, 0, 0, 0), "text.color": "grey"})

dirpath = dirname(inspect.getframeinfo(inspect.currentframe()).filename)
rootpath = abspath(dirpath + "/../../..")

# load graph

g = nngt.load_from_file(rootpath + "/testing/Networks/rat_brain.graphml",
                        attributes=["weight"],
                        cleanup=True,
                        attributes_types={"weight": float})

# prepare attributes

cc = nngt.analysis.local_clustering(g, weights="weight")

g.new_node_attribute("cc", "double", values=cc)

g.new_node_attribute("strength",
                     "double",
                     values=g.get_degrees(weights="weight"))

flux = g.get_degrees("out") - g.get_degrees("in")

g.new_node_attribute("flux", "double", values=flux)
        contour = ax.contour(xx, yy, convolved, n_contour, cmap=contour_map)
        cb = plt.colorbar(contour)
        cb.set_label('Normalized ' + Contour_Plot)

        ax.set_xlabel('x $\mu m$')
        ax.set_ylabel('y $\mu m$')

    if save_fig is not None:
        fig.save_fig(save_fig)
    if show == True:
        plt.show()


if __name__ == '__main__':
    net_file = '/home/mallory/Documents/NBs nucleation  - Internhip Mallory DAZZA/DATA/net1AS_minis0.55_mr15.0.el'
    net = nngt.load_from_file(net_file)

    edges = net.edges_array
    delay = net.get_delays()
    indegree = net.get_degrees(deg_type='in')
    outdegree = net.get_degrees(deg_type='out')
    n_nodes = net.node_nb()
    in_mean_delay = [0.] * n_nodes
    out_mean_delay = [0.] * n_nodes

    for e, (i, j) in enumerate(edges):
        in_mean_delay[j] += delay[e]
        out_mean_delay[i] += delay[e]

    for i in range(n_nodes):
        in_mean_delay[i] /= float(indegree[i])