Revision 0a4aa24d

View differences:

plotterBCrealization.py
35 35
    df = pd.read_csv(snap, names=['time', str(node_id)], skiprows=1)
36 36
    dfn = pd.concat([dfn, df[str(node_id)]], axis=1)
37 37

  
38
code.interact(local=dict(globals(), **locals()))
38
#code.interact(local=dict(globals(), **locals()))
39 39

  
40 40
print "Processing and plotting..."
41 41
if not os.path.exists("plots"+nick):
setup.ini
1 1
# Impact of Mobility Model
2 2

  
3 3
[base]
4
duration = 1000s
4
duration = 10000s
5 5
mobility_timer = 1s
6 6
max_x = 100
7 7
max_y = 100
......
37 37

  
38 38

  
39 39
[baseRWP]
40
duration = 1000s
40
duration = 10000s
41 41
nodes_number = 250
42 42
max_x = 100
43 43
max_y = 100
......
48 48
max_wait_time = 0.0
49 49

  
50 50
[baseRPG]
51
duration = 1000s
52
nodes_x_group = 5
51
duration = 10000s
52
nodes_x_group = 10
53 53
groups_number = 20
54 54
max_x = 100
55 55
max_y = 100
......
59 59
mobility_timer = 1s
60 60
mob_model = ReferencePointGroup
61 61

  
62
[heatRPG:baseRPG]
63
nodes_x_group = 10
64
groups_number = 25
65

  
62 66

  
63 67
# Impact of Radius
64 68
[ray20:baseRWP]
......
79 83
# Impact of Nodes' Density
80 84
[nn50:baseRWP]
81 85
nodes_number = 50
86
radius = 20
82 87

  
83 88
[nn100:baseRWP]
84 89
nodes_number = 100
simulator.py
13 13
import networkx as nx
14 14
import util.MyUtil as myu
15 15
from time import sleep
16
import time
16 17
import matplotlib.pyplot as plt
17 18
plt.ion()
18 19

  
19 20

  
21

  
22

  
20 23
def f(params):
21 24
    pos, radius = params['pos'], params['radius']
22 25
    # Build new UnitDiskGraph
timeAnalysis.py
13 13
import numpy as np
14 14
import glob
15 15
import matplotlib
16
import seaborn as sns
17
sns.set()
16

  
18 17

  
19 18

  
20 19
folder = sys.argv[1]
21 20
lags = 100
22 21
if len(sys.argv) > 2:
23 22
    lags = int(sys.argv[2])
24
nick = folder.split('/')[-2].split('_')[0]+"_"
23
nick = folder.split('/')[-2].split('_')[0]
25 24
os.chdir(folder)
26 25

  
27 26
bcdf = pd.DataFrame()  # rows=nodes columns=BC at column-index time-instant
......
36 35
    degdf = pd.concat([degdf, df['deg']], axis=1)
37 36
    kcoredf = pd.concat([kcoredf, df['kcore']], axis=1)
38 37

  
39

  
40 38
nodes = range(len(bcdf.columns))
41 39

  
42 40
initialCentrality = {}
......
63 61
    nodekcoreACF = pd.DataFrame(
64 62
        [kcoredf.iloc[:, node].autocorr(lag) for lag in range(lags)])
65 63
    kcoreACF = pd.concat([kcoreACF, nodekcoreACF], axis=1)
66
#code.interact(local=dict(globals(), **locals()))
67 64

  
68 65
'''
69 66
X ==> time-lag
......
76 73

  
77 74
os.chdir("plots"+nick)
78 75
# Plotting
76
code.interact(local=dict(globals(), **locals()))
77

  
78
# ACF boxplots
79
bcACF.T.boxplot(column=[1]+range(5,lags,5))
80
plt.ylabel("ACF of BC for all nodes")
81
plt.xlabel("Time-lag")
82
plt.xticks(rotation="vertical")
83
plt.axhline(y=0.2, color='k', linestyle='--', lw=1.2)
84
plt.axhline(y=0.0, color='k', linestyle='--', lw=2)
85
plt.axhline(y=-0.2, color='k', linestyle='--', lw=1.2)
86
plt.ylim(-0.4, 1.0)
87
plt.yticks(np.arange(-0.4, 1.0, step=0.1))
88
plt.savefig(nick+"autoCorrBOXPLOT-BC.pdf", format='pdf')
89
plt.clf()
90

  
91
degACF.T.boxplot(column=[1]+range(5,lags,5))
92
plt.ylabel("ACF of DEG for all nodes")
93
plt.xlabel("Time-lag")
94
plt.xticks(rotation="vertical")
95
plt.axhline(y=0.2, color='k', linestyle='--', lw=1.2)
96
plt.axhline(y=0.0, color='k', linestyle='--', lw=2)
97
plt.axhline(y=-0.2, color='k', linestyle='--', lw=1.2)
98
plt.ylim(-0.4, 1.0)
99
plt.yticks(np.arange(-0.4, 1.0, step=0.1))
100
plt.savefig(nick+"autoCorrBOXPLOT-DEG.pdf", format='pdf')
101
plt.clf()
102

  
103
kcoreACF.T.boxplot(column=[1]+range(5,lags,5))
104
plt.ylabel("ACF of KCORE for all nodes")
105
plt.xlabel("Time-lag")
106
plt.xticks(rotation="vertical")
107
plt.axhline(y=0.2, color='k', linestyle='--', lw=1.2)
108
plt.axhline(y=0.0, color='k', linestyle='--', lw=2)
109
plt.axhline(y=-0.2, color='k', linestyle='--', lw=1.2)
110
plt.ylim(-0.4, 1.0)
111
plt.yticks(np.arange(-0.4, 1.0, step=0.1))
112
plt.savefig(nick+"autoCorrBOXPLOT-KCORE.pdf", format='pdf')
113
plt.clf()
114

  
115

  
116

  
79 117
# Mean AutoCorrelation and Rank-Correlation
80 118
# lags=20
81 119
firstRank = bcdf.iloc[0, :]
......
99 137
plt.plot(x, rankCorr, lw="1.5", label='Rank-Correlation (with rank at t_0)')
100 138
# plt.plot(x, weightedRankCorr, lw="1.5",
101 139
#         label='Weighted-Rank-Correlation (with rank at t_0)')
102
plt.ylabel('Corr coeff: [ACF, Spearman rho]')
140
plt.ylabel('Correlation indexes')
103 141
plt.xlabel('Time-lags / Time')
104 142
plt.grid()
105 143
plt.legend()
......
110 148

  
111 149
toWrite = pd.concat([pd.Series(meanbcACF), pd.Series(
112 150
    meandegACF), pd.Series(meankcoreACF)], axis=1).iloc[1:, :]
113
fout = open("meanAC.csv", 'w')
151
fout = open("meanAC"+nick+".csv", 'w')
114 152
toWrite.to_csv(fout, index=False)
153
fout.close()
154

  
155
bc_deg = []
156
bc_kcore = []
157
deg_kcore = []
158
for n in nodes:
159
    bcn = bcdf.iloc[:, n]
160
    degn = degdf.iloc[:, n]
161
    kn = kcoredf.iloc[:, n]
162
    cordf = pd.concat([bcn, degn, kn], axis=1)
163
    cm = cordf.corr()
164
    bc_deg.append(cm['bc']['deg'])
165
    bc_kcore.append(cm['bc']['kcore'])
166
    deg_kcore.append(cm['deg']['kcore'])
167

  
168

  
169
a = np.mean(bc_deg)
170
b = np.mean(bc_kcore)
171
c = np.mean(deg_kcore)
172
toplotdf = pd.DataFrame([[1, a, b],
173
                         [a, 1, c],
174
                         [b, c, 1]])
175
import seaborn as sns
176
sns.set()
177

  
178
#TODO
179
#sns.heatmap(degdf.corr(), cmap="RdBu_r", center=0.0, vmin=-1.0, vmax=1.0)
180

  
181

  
182
sns.heatmap(toplotdf, cmap="RdBu_r", center=0.0, vmin=-1.0, vmax=1.0)
183
plt.savefig(nick+"meanMetricsCorrelation.pdf", format='pdf')
184
plt.clf()
185

  
186
fout = open("meanMetricsCorr"+nick+".csv", 'w')
187
toplotdf.to_csv(fout, index=False)
188
fout.close()
115 189

  
116 190
'''
117 191

  
util/MyUtil.py
13 13
    if not measures:
14 14
        measures = nx.betweenness_centrality(G, normalized = False, weight = 'weight', endpoints=True)
15 15
    measure_name = "Betweenness"
16
    nodes = nx.draw_networkx_nodes(G, lay, node_size=100, cmap=plt.cm.gnuplot2, 
16
    nodes = nx.draw_networkx_nodes(G, lay, node_size=25, cmap=plt.cm.gnuplot2, 
17 17
                                   node_color=measures.values(),
18 18
                                   nodelist=measures.keys())
19 19
    nodes.set_norm(mcolors.SymLogNorm(linthresh=0.01, linscale=1))
util/UnitDiskGraph.py
4 4
from scipy.spatial import KDTree
5 5
from scipy.spatial.distance import cdist
6 6
import code  # code.interact(local=dict(globals(), **locals()))
7
import graph_tool as gt
7
import graph_tool.all as gt
8
import numpy as np
9
from pprint import pprint
10
import time
11
from heapq import nsmallest
12
from collections import defaultdict
13

  
14
def second_smallest(numbers):
15
    return nsmallest(2, numbers)[-1]
16

  
17

  
18
def reconnectGraph(g, distM):
19
    labels, hist=gt.label_components(g, directed=False)
20
    # While not only a single component
21
    while (not all(e==0 for e in labels.a)):
22
        #code.interact(local=dict(globals(), **locals()))
23
        # Divide node by component
24
        comp2nodes = defaultdict(list)
25
        for i in range(len(labels.a)):
26
            comp2nodes[labels.a[i]].append(i)
27
        # se il grafo e' sconnesso solo per un singolo nodo staccato
28
        if len(set(labels.a))==2 and min(map(len, comp2nodes.values()))==1:
29
            #print "Isolated node"
30
            #code.interact(local=dict(globals(), **locals()))
31
            out=g.get_out_degrees(g.get_vertices())
32
            for i in range(0,len(out),1):
33
                if out[i]==0:
34
                    dp=distM[i]
35
                    closest=second_smallest(dp)
36
                    near_neigh=[k for k in range(len(dp)) if dp[k]==closest][0]
37
                    g.add_edge(g.vertex(i), g.vertex(near_neigh))
38
                    break   
39
        else:
40
            #iteratively attach the smallest compo to the closest
41
            #print "Separated Compo"
42
            #code.interact(local=dict(globals(), **locals()))
43
            d={k:len(v) for k,v in comp2nodes.items()}
44
            minCompoLabel=min(d, key=d.get)
45
            minCompo=comp2nodes[minCompoLabel]
46
            couple=None
47
            nearest_dist=10000000
48
            for n in minCompo:
49
                dp=distM[n]
50
                for v in range(0,len(distM), 1):
51
                    if n==v: continue
52
                    if labels.a[v] == labels.a[n]: continue
53
                    closest=distM[n][v]
54
                    if closest < nearest_dist:
55
                        nearest_dist = closest
56
                        couple=n,v
57
            g.add_edge(g.vertex(couple[0]), g.vertex(couple[1]))
58
            #print "Connecting %d--%d, which are %.04f distant" % (couple[0], couple[1], nearest_dist)
59

  
60
        labels, hist=gt.label_components(g, directed=False)
61

  
8 62

  
9 63
class UnitDiskGraph:
10 64

  
......
45 99
        self.gtG.ep["weight"] = self.gtG.new_edge_property("float")
46 100
        eprops = [self.gtG.ep["weight"]]
47 101
        self.gtG.add_edge_list(edges, eprops=eprops)
102
        #out=self.gtG.get_out_degrees(self.gtG.get_vertices())
103
        reconnectGraph(self.gtG, distM)
104
            
48 105

  
49 106
    def getGraph(self):
50 107
        return self.gtG, self.nxG
108

  
109
    
110

  
111

  
112

  
113

  
114

  
115

  

Also available in: Unified diff