Beispiel #1
0
    def test_degree(self):
        g = dn.DynGraph()
        g.add_path([0, 1, 2, 3, 4], t=5)
        g.add_path([4, 5, 6, 7, 8], t=6)

        ng = g.degree(4)
        self.assertEqual(ng, 2)

        ng = g.degree(4, 5)
        self.assertEqual(ng, 1)

        ng = g.degree(4, 6)
        self.assertEqual(ng, 1)

        ng = g.degree(4, 0)
        self.assertEqual(ng, 0)
Beispiel #2
0
    def test_stream_interactions(self):
        g = dn.DynGraph()
        g.add_interaction(1, 2, 2)
        g.add_interaction(1, 2, 2, e=6)
        g.add_interaction(1, 2, 7, e=11)
        g.add_interaction(1, 2, 8, e=15)
        g.add_interaction(1, 2, 18)
        g.add_interaction(1, 2, 19)
        g.add_interactions_from([(1, 3), (1, 5)], t=2, e=3)

        sres = list(g.stream_interactions())

        cres = [(1, 2, '+', 2), (1, 3, '+', 2), (1, 5, '+', 2), (1, 3, '-', 3),
                (1, 5, '-', 3), (1, 2, '-', 6), (1, 2, '+', 7),
                (1, 2, '-', 15), (1, 2, '+', 18)]
        self.assertEquals(sorted(sres), sorted(cres))
Beispiel #3
0
    def test_number_of_nodes(self):
        g = dn.DynGraph()
        g.add_path([0, 1, 2, 3, 4], t=5)
        g.add_path([4, 5, 6, 7, 8], t=6)

        nn = g.number_of_nodes()
        self.assertEqual(nn, 9)

        nn = g.number_of_nodes(t=5)
        self.assertEqual(nn, 5)

        nn = g.number_of_nodes(t=0)
        self.assertEqual(nn, 0)

        avg = g.avg_number_of_nodes()
        self.assertEqual(avg, 5)
Beispiel #4
0
    def test_neighbores(self):
        g = dn.DynGraph()
        g.add_path([0, 1, 2, 3, 4], t=5)
        g.add_path([4, 5, 6, 7, 8], t=6)

        ng = len(g.neighbors(0))
        self.assertEqual(ng, 1)

        ng = len(g.neighbors(0, 5))
        self.assertEqual(ng, 1)

        ng = len(g.neighbors(0, 6))
        self.assertEqual(ng, 0)

        ng = len(g.neighbors(0, 0))
        self.assertEqual(ng, 0)
Beispiel #5
0
    def test_inter_event_time(self):
        g = dn.DynGraph()
        g.add_path([0, 1, 2, 3, 4], t=2)
        g.add_path([4, 5, 6, 7, 8], t=3)

        ivt = g.inter_event_time_distribution()
        self.assertDictEqual(ivt, {0: 6, 1: 1})

        ivt = g.inter_event_time_distribution(4)
        self.assertDictEqual(ivt, {1: 1})

        ivt = g.inter_event_time_distribution(0)
        self.assertDictEqual(ivt, {})

        ivt = g.inter_event_time_distribution(0, 1)
        self.assertDictEqual(ivt, {})
Beispiel #6
0
 def test_snapshots_interactions(self):
     g = dn.DynGraph()
     g.add_interaction(1, 2, 2)
     g.add_interaction(1, 2, 2, e=6)
     g.add_interaction(1, 2, 7, e=11)
     g.add_interaction(1, 2, 8, e=15)
     g.add_interaction(1, 2, 18)
     g.add_interaction(1, 2, 19)
     dn.write_snapshots(g, "test.txt", delimiter=" ")
     h = dn.read_snapshots("test.txt", nodetype=int, timestamptype=int)
     self.assertEqual(g.number_of_interactions(), h.number_of_interactions())
     self.assertEqual(list(g.stream_interactions()), list(h.stream_interactions()))
     dn.write_interactions(h, "test.txt", delimiter=" ")
     h = dn.read_interactions("test.txt", nodetype=int, timestamptype=int, keys=True)
     dn.write_snapshots(h, "test.txt", delimiter=" ")
     os.remove("test.txt")
Beispiel #7
0
 def test_interaction_graph_directed(self):
     g = dn.DynGraph()
     g.add_interaction(1, 2, 2)
     g.add_interaction(1, 2, 2, e=6)
     g.add_interaction(1, 2, 7, e=11)
     g.add_interaction(1, 2, 8, e=15)
     g.add_interaction(1, 2, 18)
     g.add_interaction(1, 2, 19)
     dn.write_interactions(g, "test2.txt", delimiter=" ")
     h = dn.read_interactions("test2.txt",
                              directed=True,
                              nodetype=int,
                              timestamptype=int)
     self.assertEqual(list(g.stream_interactions()),
                      list(h.stream_interactions()))
     self.assertEqual(g.number_of_interactions(),
                      h.number_of_interactions())
     os.remove("test2.txt")
Beispiel #8
0
 def test_accumulative_growth(self):
     g = dn.DynGraph(edge_removal=False)
     g.add_interaction(1, 2, 2)
     g.add_interaction(1, 2, 2, e=6)
     g.add_interaction(1, 2, 7, e=11)
     g.add_interaction(1, 2, 8, e=15)
     g.add_interaction(1, 2, 18)
     g.add_interaction(1, 2, 19)
     g.add_interactions_from([(1, 3), (1, 5)], t=2, e=3)
     sres = list(g.stream_interactions())
     cres = [(1, 2, '+', 2), (1, 5, '+', 2), (1, 3, '+', 2)]
     self.assertEqual(sorted(sres), sorted(cres))
     self.assertEqual(g.has_interaction(1, 2, 18), True)
     self.assertEqual(g.has_interaction(1, 2, 40), False)
     try:
         g.add_interaction(2, 1, 7)
     except:
         pass
Beispiel #9
0
    def test_DynSI(self):
        dg = dn.DynGraph()

        for t in past.builtins.xrange(0, 3):
            g = nx.erdos_renyi_graph(200, 0.05)
            dg.add_interactions_from(g.edges(), t)

        model = si.DynSIModel(dg)
        config = mc.Configuration()
        config.add_model_parameter('beta', 0.1)
        config.add_model_parameter("percentage_infected", 0.1)
        model.set_initial_status(config)
        iterations = model.execute_snapshots()
        self.assertEqual(len(iterations), 3)

        iterations = model.execute_iterations()
        trends = model.build_trends(iterations)
        self.assertEqual(len(trends[0]['trends']['status_delta'][1]),
                         len([x for x in dg.stream_interactions() if x[2] == "+"]))
Beispiel #10
0
    def test_visualize_dynamic(self):
        dg = dn.DynGraph()

        for t in past.builtins.xrange(0, 4):
            g = nx.erdos_renyi_graph(200, 0.05)
            dg.add_interactions_from(g.edges(), t)

        model = dsi.DynSIModel(dg)
        config = mc.Configuration()
        config.add_model_parameter('beta', 0.1)
        config.add_model_parameter("percentage_infected", 0.1)
        model.set_initial_status(config)
        iterations = model.execute_snapshots()
        trends = model.build_trends(iterations)

        # Visualization
        viz = DiffusionPrevalence(model, trends)
        viz.plot("prevd.pdf")
        os.remove("prevd.pdf")
Beispiel #11
0
    def test_number_of_interactions(self):
        g = dn.DynGraph()
        g.add_path([0, 1, 2, 3, 4], t=5)
        g.add_path([4, 5, 6, 7, 8], t=6)

        its = g.number_of_interactions()
        self.assertEqual(its, 8)

        its = g.number_of_interactions(0)
        self.assertEqual(its, None)

        its = g.number_of_interactions(0, 1)
        self.assertEqual(its, 1)

        its = g.number_of_interactions(0, 1, 5)
        self.assertEqual(its, 1)

        its = g.number_of_interactions(0, 1, 6)
        self.assertEqual(its, 0)
Beispiel #12
0
    def test_nodes(self):
        g = dn.DynGraph()
        g.add_star([0, 1, 2, 3, 4], t=5)
        nds = len(g.nodes())
        self.assertEqual(nds, 5)

        g.add_star([5, 1, 2, 3, 4], t=6)
        nds = len(g.nodes())
        self.assertEqual(nds, 6)

        nds = len(g.nodes(t=6))
        self.assertEqual(nds, 5)

        nds = len(g.nodes(t=9))
        self.assertEqual(nds, 0)

        self.assertEqual(g.has_node(0), True)
        self.assertEqual(g.has_node(0, 5), True)
        self.assertEqual(g.has_node(0, 6), False)
        self.assertEqual(g.has_node(0, 0), False)
Beispiel #13
0
    def test_DynProfile(self):
        dg = dn.DynGraph()

        for t in past.builtins.xrange(0, 3):
            g = nx.erdos_renyi_graph(200, 0.05)
            dg.add_interactions_from(g.edges(), t)

        model = pro.DynProfileModel(dg)
        config = mc.Configuration()
        config.add_model_parameter("percentage_infected", 0.1)
        config.add_model_parameter("blocked", 0.1)
        config.add_model_parameter("adopter_rate", 0.001)

        profile = 0.1
        for i in g.nodes():
            config.add_node_configuration("profile", i, profile)

        model.set_initial_status(config)
        model.set_initial_status(config)
        iterations = model.execute_snapshots()
        self.assertEqual(len(iterations), 3)
Beispiel #14
0
    def test_time_slice(self):
        g = dn.DynGraph()
        g.add_path([0, 1, 2, 3, 4], t=5)
        g.add_path([4, 5, 6, 7, 8], t=6)

        h = g.time_slice(5)
        self.assertIsInstance(h, dn.DynGraph)
        self.assertEqual(h.number_of_nodes(), 5)
        self.assertEqual(h.number_of_interactions(), 4)

        h = g.time_slice(5, 5)
        self.assertIsInstance(h, dn.DynGraph)
        self.assertEqual(h.number_of_nodes(), 5)
        self.assertEqual(h.number_of_interactions(), 4)

        h = g.time_slice(5, 6)
        self.assertIsInstance(h, dn.DynGraph)
        self.assertEqual(h.number_of_nodes(), 9)
        self.assertEqual(h.number_of_interactions(), 8)

        h = g.time_slice(0)
        self.assertIsInstance(h, dn.DynGraph)
        self.assertEqual(h.number_of_nodes(), 0)
        self.assertEqual(h.number_of_interactions(), 0)
Beispiel #15
0
    def test_dyngraph_add_interaction(self):
        g = dn.DynGraph()
        self.assertIsInstance(g, dn.DynGraph)

        g.add_interaction(1, 2, 2)
        g.add_interaction(1, 2, 2, e=6)
        g.add_interaction(1, 2, 7, e=11)
        g.add_interaction(1, 2, 8, e=15)
        g.add_interaction(1, 2, 18)
        g.add_interaction(1, 2, 19)

        its = g.interactions()
        self.assertEqual(len(its), 1)

        g.add_interactions_from([(1, 3), (1, 5)], t=2)

        its = g.interactions()
        self.assertEqual(len(its), 3)

        its = g.interactions(t=18)
        self.assertEqual(len(its), 1)

        its = g.interactions(t=20)
        self.assertEqual(len(its), 0)

        self.assertEqual(len(list(g.neighbors_iter(1))), 3)
        self.assertEqual(len(list(g.neighbors_iter(1, 7))), 1)
        self.assertEqual(len(list(g.neighbors_iter(1, 0))), 0)
        self.assertEqual(g.order(), len(g.nodes()))

        self.assertEqual(g.has_node(42), False)

        self.assertEqual(g.has_node(42, 3), False)
        g.add_cycle([3, 4, 5, 6], t=34)
        try:
            g.time_slice(2, 1)
        except:
            pass

        g.interactions_iter([1, 2])

        try:
            g.add_interaction(1, 5)
        except:
            pass

        try:
            g.add_interactions_from([(1, 4), (3, 6)])
        except:
            pass

        try:
            g.remove_edge(1, 2)
        except:
            pass

        try:
            g.remove_edges_from([(1, 2)])
        except:
            pass
        try:
            g.remove_node(1)
        except:
            pass
        try:
            g.remove_nodes_from([1, 2])
        except:
            pass

        self.assertEqual(g.number_of_interactions(1, 90), 0)
Beispiel #16
0
    def test_functions(self):
        g = dn.DynGraph()
        g.add_interaction(1, 2, 2)
        g.add_interaction(1, 2, 2, e=6)
        g.add_interaction(1, 2, 7, e=11)
        g.add_interaction(1, 2, 8, e=15)
        g.add_interaction(1, 2, 18)
        g.add_interaction(1, 2, 19)

        self.assertEqual(len(dn.nodes(g)), 2)
        self.assertEqual(len(dn.nodes(g, t=0)), 0)
        self.assertEqual(len(dn.nodes(g, t=2)), 2)
        self.assertEqual(len(dn.interactions(g)), 1)
        self.assertEqual(len(dn.interactions(g, t=0)), 0)
        self.assertEqual(len(dn.interactions(g, t=2)), 1)
        self.assertDictEqual(dn.degree(g), {1: 1, 2: 1})
        self.assertDictEqual(dn.degree(g, t=0), {1: 0, 2: 0})
        self.assertDictEqual(dn.degree(g, [1, 2]), {1: 1, 2: 1})
        self.assertEqual(len(dn.neighbors(g, 1)), 1)
        self.assertEqual(len(dn.neighbors(g, 1, t=2)), 1)
        self.assertEqual(len(dn.neighbors(g, 1, t=0)), 0)
        self.assertEqual(dn.number_of_nodes(g), 2)
        self.assertEqual(dn.number_of_nodes(g, t=0), 0)
        self.assertEqual(dn.number_of_nodes(g, t=2), 2)
        self.assertEqual(dn.number_of_interactions(g, t=0), 0)
        self.assertEqual(dn.number_of_interactions(g, t=2), 1)
        self.assertEqual(dn.number_of_interactions(g), 1)
        self.assertEqual(dn.density(g), 1.0)
        self.assertEqual(dn.density(g, t=0), 0)
        self.assertEqual(dn.density(g, t=2), 0)
        self.assertEqual(dn.degree_histogram(g), [0, 2])
        self.assertEqual(dn.degree_histogram(g, t=0), [2])
        self.assertEqual(dn.degree_histogram(g, t=2), [0, 2])
        self.assertEqual(dn.is_directed(g), False)

        dn.add_cycle(g, [1, 2, 3, 4], t=30)
        dn.add_path(g, [4, 6, 7, 8], t=40)
        dn.add_star(g, [1, 2, 3, 4], t=50)
        dn.subgraph(g, [1, 3, 4])
        dn.create_empty_copy(g)

        self.assertEqual(len(dn.all_neighbors(g, 1, t=0)), 0)
        self.assertEqual(len(dn.all_neighbors(g, 1)), 3)
        self.assertEqual(len(dn.all_neighbors(g, 1, t=2)), 1)
        self.assertEqual(len(list(dn.non_neighbors(g, 1, t=0))), 6)
        self.assertEqual(len(list(dn.non_neighbors(g, 1))), 3)
        self.assertEqual(len(list(dn.non_neighbors(g, 1, t=2))), 5)
        dn.non_interactions(g, 2)
        dn.non_interactions(g, 0)
        dn.non_interactions(g)
        self.assertEqual(dn.is_empty(g), False)
        h = dn.DynGraph()
        self.assertEqual(dn.is_empty(h), True)
        h = dn.time_slice(g, 2, 4)
        self.assertEqual(len(h.nodes()), 2)
        dn.stream_interactions(g)
        dn.temporal_snapshots_ids(g)
        dn.interactions_per_snapshots(g, 0)
        dn.interactions_per_snapshots(g, 2)
        dn.interactions_per_snapshots(g)
        dn.inter_event_time_distribution(g)
        dn.inter_event_time_distribution(g, 1)
        dn.inter_event_time_distribution(g, 1, 2)
        dn.set_node_attributes(g,
                               values={n: 0
                                       for n in g.nodes()},
                               name="test")
        try:
            dn.set_node_attributes(g, values={90000: 0}, name="test")
        except:
            pass
        try:
            dn.set_node_attributes(g, "test1", name="test")
        except:
            pass
        dn.set_node_attributes(g, values={n: {"a": 3} for n in g.nodes()})
        try:
            dn.set_node_attributes(g, values={9000: {"a": 3}})
        except:
            pass

        dn.get_node_attributes(g, name="test")
        try:
            dn.set_edge_attributes(g, 3, "dog")
        except:
            pass
        try:
            dn.get_edge_attributes(g, "test")
        except:
            pass

        dn.freeze(g)
        self.assertEqual(dn.is_frozen(g), True)

        h = g.to_directed()
        dn.all_neighbors(h, 1)

        self.assertEqual(len(list(dn.non_interactions(g))), 13)
import networkx as nx
import numpy as np
import matplotlib
import dynetx as dn
import matplotlib.pyplot as plt

plt.close("all")
'''
plt.figure()
G= nx.Graph()
G.add_edge('a','b',timestamp='t1')
G.add_node('c',timestamp='t1')

G.add_edge('a','b',timestamp='t2')
G.add_edge('a','c',timestamp='t2')
G.add_edge('b','c',timestamp='t2')

'''
plt.figure()
G = dn.DynGraph(edge_removal=True)
G.add_path([0, 1, 2], 0)
dn.nodes(G, t=0)
G.add_edge(2, 3, t=1)
dn.interactions(G, t=0)

#G.add_interaction(u=1, v=2, t=0, e=3)
nx.draw(G)
plt.show()
        'node_color': 'cyan',
        'node_size': 1,
        'line_color': 'red',
        'linewidths': 0,
        'width': 0.1,
}
nx.draw_circular(G, **options)
plt.show()

G=nx.read_edgelist("/Users/jennie/Documents/analytics/xanax/xanshort.csv", delimiter=",")

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

g = dn.DynGraph(edge_removal=False)
g = dn.read_snapshots("/Users/jennie/Documents/analytics/xanax/lyrics_ngrams.txt", timestamptype=int)
pos=nx.spring_layout(g,scale=20) # double distance between all nodes
plt.figure(3,figsize=(10,10)) 
nx.draw(g,pos,node_size=10, font_size=8, with_labels=True)


list(g.stream_interactions())



import networkx as nx
import ndlib.models.ModelConfig as mc
import ndlib.models.opinions.AlgorithmicBiasModel as ab

# Network topology
    def test_dyn_edge_stochastic(self):

        # Fixed Threshold
        dg = dn.DynGraph()

        for t in past.builtins.xrange(0, 3):
            g = nx.erdos_renyi_graph(200, 0.05)
            dg.add_interactions_from(g.edges(), t)

        model = gc.DynamicCompositeModel(dg)

        model.add_status("Susceptible")
        model.add_status("Infected")

        c1 = cpm.EdgeStochastic(0.1, triggering_status="Infected")
        model.add_rule("Susceptible", "Infected", c1)

        config = mc.Configuration()
        config.add_model_parameter('percentage_infected', 0.1)

        model.set_initial_status(config)
        iterations = model.execute_snapshots()
        self.assertEqual(len(iterations), 3)

        iterations = model.execute_iterations()
        trends = model.build_trends(iterations)
        self.assertEqual(
            len(trends[0]['trends']['status_delta'][1]),
            len([x for x in dg.stream_interactions() if x[2] == "+"]))

        # Ad-hoc Threshold
        model = gc.DynamicCompositeModel(dg)

        model.add_status("Susceptible")
        model.add_status("Infected")

        c1 = cpm.EdgeStochastic(triggering_status="Infected")
        model.add_rule("Susceptible", "Infected", c1)

        config = mc.Configuration()

        for e in g.edges():
            config.add_edge_configuration("threshold", e,
                                          np.random.random_sample())

        config.add_model_parameter('percentage_infected', 0.1)

        model.set_initial_status(config)
        iterations = model.execute_snapshots()
        self.assertEqual(len(iterations), 3)

        iterations = model.execute_iterations()
        trends = model.build_trends(iterations)
        self.assertEqual(
            len(trends[0]['trends']['status_delta'][1]),
            len([x for x in dg.stream_interactions() if x[2] == "+"]))

        # Predefined threshold 1/N
        model = gc.DynamicCompositeModel(dg)

        model.add_status("Susceptible")
        model.add_status("Infected")

        c1 = cpm.EdgeStochastic(triggering_status="Infected")
        model.add_rule("Susceptible", "Infected", c1)

        config = mc.Configuration()
        config.add_model_parameter('percentage_infected', 0.1)

        model.set_initial_status(config)
        iterations = model.execute_snapshots()
        self.assertEqual(len(iterations), 3)

        iterations = model.execute_iterations()
        trends = model.build_trends(iterations)
        self.assertEqual(
            len(trends[0]['trends']['status_delta'][1]),
            len([x for x in dg.stream_interactions() if x[2] == "+"]))
Beispiel #20
0
def RDyn(
    size: int = 300,
    iterations: int = 5,
    avg_deg: int = 15,
    sigma: float = 0.6,
    lambdad: float = 1,
    alpha: float = 2.5,
    paction: float = 1,
    prenewal: float = 0.8,
    quality_threshold: float = 0.5,
    new_node: float = 0.0,
    del_node: float = 0.0,
    max_evts: int = 1,
    simplified: bool = True,
) -> [dn.DynGraph, object]:
    """
    RDyn is a syntetic dynamic network generator with time-dependent ground-truth partitions having tunable quality (in terms of conductance).
    Communities' ids are aligned across time and a predefined number of merge/plit events are planted in between consecutive stable iterations.

    :param size: Number of nodes
    :param iterations: Number of stable iterations
    :param avg_deg: Average node degree. Int, default 15
    :param sigma: Percentage of node's edges within a community. Float, default .6
    :param lambdad: Community size distribution exponent. Float, default 1
    :param alpha:  Degree distribution exponent. Float, default 2.5
    :param paction: Probability of node action. Float, default 1
    :param prenewal: Probability of edge renewal. Float, default, .8
    :param quality_threshold: Conductance quality threshold for stable iteration. Float, default .5
    :param new_node: Probability of node appearance. Float, default 0
    :param del_node: Probability of node vanishing. Float, default 0
    :param max_evts: Max number of community events for stable iteration. Int, default 1
    :param simplified: Simplified execution. Boolean, default True. (NB: when True an approximation of the original process is executed - some network characteristics can deviate from the expected ones)

    :return: A dynetx DynGraph, the TemporalClustering object

    :Example:

    >>> from cdlib.benchmark import RDyn
    >>> G, coms = RDyn(n=300)

    :References:

    Rossetti, Giulio. "RDyn: graph benchmark handling community dynamics." Journal of Complex Networks 5.6 (2017): 893-912.

    .. note:: Reference implementation: https://github.com/GiulioRossetti/RDyn
    """
    tc = TemporalClustering()
    dg = dn.DynGraph()
    rdb = rdyn.RDynV2(
        size=size,
        iterations=iterations,
        avg_deg=avg_deg,
        quality_threshold=quality_threshold,
        sigma=sigma,
        lambdad=lambdad,
        alpha=alpha,
        paction=paction,
        prenewal=prenewal,
        new_node=new_node,
        del_node=del_node,
        max_evts=max_evts,
    )

    t = 0
    for g, communities in rdb.execute(simplified=simplified):
        dg.add_interactions_from(g.edges(), t=t, e=t)
        sg = dg.time_slice(t)
        nc = NamedClustering(
            communities,
            sg,
            "RDyn",
            {
                "size": size,
                "iterations": iterations,
                "avg_deg": avg_deg,
                "quality_threshold": quality_threshold,
                "sigma": sigma,
                "lambdad": lambdad,
                "alpha": alpha,
                "paction": paction,
                "prenewal": prenewal,
                "new_node": new_node,
                "del_node": del_node,
                "max_evts": max_evts,
                "simplified": simplified,
            },
            overlap=False,
        )
        tc.add_clustering(nc, time=t)
        t += 1

    return dg, tc