Revision 23c7ab1e

View differences:

plotterBCrealization.py
16 16
import seaborn as sns
17 17
sns.set()
18 18

  
19

  
20

  
21
# https://en.wikipedia.org/wiki/Sample_entropy
22
def SampEn(U, m, r):
23
    """Compute Sample entropy"""
24
    def _maxdist(x_i, x_j):
25
        return max([abs(ua - va) for ua, va in zip(x_i, x_j)])
26

  
27
    def _phi(m):
28
        x = [[U[j] for j in range(i, i + m - 1 + 1)] for i in range(N - m + 1)]
29
        C = [len([1 for j in range(len(x)) if i != j and _maxdist(x[i], x[j]) <= r]) for i in range(len(x))]
30
        return sum(C)
31

  
32
    N = len(U)
33
    return -np.log(_phi(m+1) / _phi(m))
34

  
35
ss = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/sunspotarea.csv')
36
a10 = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/a10.csv')
37
rand_small = np.random.randint(0, 100, size=36)
38
rand_big = np.random.randint(0, 100, size=136)
39

  
40
print(SampEn(ss.value, m=2, r=0.2*np.std(ss.value)))      # 0.78
41
print(SampEn(a10.value, m=2, r=0.2*np.std(a10.value)))    # 0.41
42
print(SampEn(rand_small, m=2, r=0.2*np.std(rand_small)))  # 1.79
43
print(SampEn(rand_big, m=2, r=0.2*np.std(rand_big)))      # 2.42
44

  
45

  
46

  
19 47
folder = sys.argv[1]
20 48
interval = 100
21 49
if len(sys.argv) > 2:
......
33 61
    df = pd.read_csv(snap, names=['time', str(node_id)], skiprows=1)
34 62
    dfn = pd.concat([dfn, df[str(node_id)]], axis=1)
35 63

  
64
code.interact(local=dict(globals(), **locals()))
36 65

  
37 66
print "Processing and plotting..."
38 67
if not os.path.exists("plots"+nick):
......
164 193
#            'label': '\"Core Or Not\" (Blue or White)'})
165 194

  
166 195
small=pd.DataFrame(resDF.iloc[:,0:1000])
167
sns.heatmap(small, cmap=cmap1, xticklabels=range(1000), yticklabels=range(len(small)), cbar_kws={
196
#code.interact(local=dict(globals(), **locals()))
197
sns.heatmap(small.applymap(int), cmap=cmap1, xticklabels=range(1000), yticklabels=range(len(small)), cbar_kws={
168 198
            'label': '\"Core Or Not\" (Blue or White)'})
169 199

  
170 200
plt.savefig(nick+"coreResistMap-EntryTOP10LeavingTOP20.pdf", format='pdf')
......
212 242

  
213 243
f = open(nick + "stats.txt", 'w')
214 244
f.write(str(pd.DataFrame(allint).describe()))
215
f.close()
245
f.close()
settings.ini
1
[baseRPG]
2
duration = 1000s
3
nodes_x_group = 5
4
groups_number = 20
5
max_x = 100
6
max_y = 100
7
min_velocity = 0.1
8
max_velocity = 1.0
9
aggregation = 0.1
10
radius = 30.0
11
mobility_timer = 1s
12
mob_model = ReferencePointGroup
13

  
14
[rpgAGG2:baseRPG]
15
aggregation = 0.2
16

  
17
[rpgAGG5:baseRPG]
18
aggregation = 0.5
19

  
20
[rpgAGG7:baseRPG]
21
aggregation = 0.7
22

  
23
[rpgAGG9:baseRPG]
24
aggregation = 0.9
25

  
26

  
1 27
[milano]
2 28
duration = 100s
3 29
nodes_number = 1000
......
46 72
nodes_number = 750
47 73
radius = 30.0
48 74

  
49
[rwpR30N1000:baseRWP]
50
nodes_number = 1000
51
radius = 30.0
52 75

  
53 76
# 50 nodi
54 77
[rwpR30N50.0:baseRWP]
setup.ini
1
[baseRWP]
2
duration = 1000s
3
nodes_number = 250
4
max_x = 100
5
max_y = 100
6
velocity = pedestrian
7
radius = 30.0
8
mobility_timer = 1s
9
mob_model = RandomWayPoint
10
max_wait_time = 0.0
11

  
12
[baseRPG]
13
duration = 1000s
14
nodes_x_group = 5
15
groups_number = 20
16
max_x = 100
17
max_y = 100
18
velocity = pedestrian
19
aggregation = 0.5
20
radius = 30.0
21
mobility_timer = 1s
22
mob_model = ReferencePointGroup
23

  
24
[milano]
25
duration = 1000s
26
nodes_number = 1000
27
max_x = 100
28
max_y = 100
29
radius = 30.0
30
mobility_timer = 1s
31
mob_model = Milan
32

  
33

  
34
# Impact of Radius
35
[ray20:baseRWP]
36
radius = 20.0
37

  
38
[ray25:baseRWP]
39
radius = 25.0
40

  
41
[ray30:baseRWP]
42
radius = 30.0
43

  
44
[ray35:baseRWP]
45
radius = 35.0
46

  
47
[ray40:baseRWP]
48
radius = 40.0
49

  
50
# Impact of Nodes' Density
51
[nn50:baseRWP]
52
nodes_number = 50
53

  
54
[nn100:baseRWP]
55
nodes_number = 100
56

  
57
[nn250:baseRWP]
58
nodes_number = 250
59

  
60
[nn500:baseRWP]
61
nodes_number = 500
62

  
63
[nn750:baseRWP]
64
nodes_number = 750
65

  
66
[nn1000:baseRWP]
67
nodes_number = 1000
68

  
69
[nn4000:baseRWP]
70
nodes_number = 4000
71

  
72

  
73
# Impacts of speed
74

  
75
[speed_slow:baseRWP]
76
velocity = slow
77

  
78
[speed_pedestrian:baseRWP]
79
velocity = pedestrian
80

  
81
[speed_jogging:baseRWP]
82
velocity = jogging
83

  
84
[speed_bike:baseRWP]
85
velocity = bike
86

  
87
[speed_citycar:baseRWP]
88
velocity = citycar
simulator.py
1
import graph_tool.centrality as gtc
1
import graph_tool.all as gt
2 2
import warnings
3 3
import util.EventScheduler as ES
4 4
from tqdm import tqdm  # https://pypi.org/project/tqdm/#usage
......
9 9

  
10 10
import random
11 11
import code  # code.interact(local=dict(globals(), **locals()))
12

  
12
from pprint import pprint
13 13
import networkx as nx
14 14
import util.MyUtil as myu
15
import util.nx2gt as nx2gt
16 15
from time import sleep
17 16
import matplotlib.pyplot as plt
18 17
plt.ion()
......
22 21
    pos, radius = params['pos'], params['radius']
23 22
    # Build new UnitDiskGraph
24 23
    G, nxG = UnitDiskGraph(pos, radius).getGraph()
24
    params['gtG'] = G
25 25
    params['nxG'] = nxG
26 26
    ws = G.edge_properties["weight"]
27
    vp, ep = gtc.betweenness(G, norm=False, weight=ws)
27
    vp, ep = gt.betweenness(G, norm=False, weight=ws)
28 28
    btwd = {i: vp.a[i] for i in range(len(vp.a))}
29 29
    params['btw'] = btwd
30
    kcore = gt.kcore_decomposition(G)
31
    kcd = {i: kcore.a[i] for i in range(len(kcore.a))}
32
    params['kcore'] = kcd
33
    deg = G.degree_property_map("out")
34
    degd = {i: deg.a[i] for i in range(len(deg.a))}
35
    params['deg'] = degd
30 36
    return params
31 37

  
32 38

  
......
46 52
        for i in range(NN):
47 53
            f = open(outPath+"/stats"+'%08d' % i+".csv", 'a+')
48 54
            self.statsFiles[i] = f
49
            f.write("Time,BC\n")
55
            f.write("Time,BC,DEG,KCORE\n")
50 56

  
51 57
    def batch_tasks(self, sched, mobi, num_workers=5):
52 58
        # prepare next num_workers tasks
......
81 87
                current = sched.processed_events()
82 88
                pbar.update(current-prev)
83 89

  
84
                #code.interact(local=dict(globals(), **locals()))
85 90
                # Log results to disk
86 91
                for res in results:
87
                    self.logBTW(res['btw'], res['tag'])
92
                    #code.interact(local=dict(globals(), **locals()))
93
                    self.logRes(res, stats=['btw', 'deg', 'kcore'])
88 94

  
89
                #code.interact(local=dict(globals(), **locals()))
90 95
                if self.gui and self.num_workers == 1:
91 96
                    res = results[0]
92 97
                    self.draw(res['nxG'], res['pos'], res['btw'])
......
96 101
            self.statsFiles[f].close()
97 102
        return
98 103

  
99
    def logBTW(self, btw, tag):
100
        tag = '%08d' % tag
101
        for n, bc in btw.items():
102
            self.statsFiles[n].write(tag+","+str(bc)+"\n")
104
    def logRes(self, res, stats):
105
        tag = '%08d' % res['tag']
106
        for n in range(self.params['nodes_number']):
107
            btw = res['btw'][n]
108
            deg = res['deg'][n]
109
            kcore = res['kcore'][n]
110
            self.statsFiles[n].write(
111
                ",".join(map(str, [tag, btw, deg, kcore]))+"\n")
103 112

  
104 113
    def draw(self, G, pos, measures=None):
105 114
        xmax = self.params['max_x']
timeAnalysis.py
45 45
dfACF = pd.DataFrame()  # rows=Time-Lags, columns = nodes
46 46
print "Processing data..."
47 47
for node in nodes:
48
    print "Autocorr of node", node
48
    #print "Autocorr of node", node
49 49
    nodeACF = pd.DataFrame([dfn[node].autocorr(lag) for lag in range(lags)])
50 50
    dfACF = pd.concat([dfACF, nodeACF], axis=1)
51 51

  
......
129 129

  
130 130
X, Y, Z = [], [], []
131 131
for node in srtNodes:
132
    print "n:", node
132
    #print "n:", node
133 133
    for lag in range(lags):
134
        print "\tn:%d  lag:%d" % (node,lag)
134
        #print "\tn:%d  lag:%d" % (node,lag)
135 135
        #code.interact(local=dict(globals(), **locals()))
136 136
        X.append(lag)
137 137
        Y.append(node)
util/ConfPars.py
6 6
from milanoMob import milano_mob
7 7
import code  # code.interact(local=dict(globals(), **locals()))
8 8

  
9

  
9 10
class ConfSettings(object):
10 11

  
11 12
    def __init__(self, settingsFile, sectionExp):
......
13 14
        self.SEC = sectionExp
14 15
        # return self.getSimulationParameters(settingsFile, sectionExp)
15 16

  
17
    def getVelocity(self, kind):
18
        velMap = {'slow': (0.139, 0.556), 'pedestrian': (0.556, 1.667), 'jogging': (
19
            1.667, 3.332), 'bike': (3.332, 8.332), 'citycar': (8.332, 22.223)}
20
        if kind not in velMap:
21
            return velMap['pedestrian']
22
        else:
23
            return velMap[kind]
24

  
16 25
    def getSimulationParameters(self):
17 26
        settingsFile, sectionExp = self.SF, self.SEC
18 27
        retParameters = {}
......
44 53
                retParameters['max_x'] = int(arg)
45 54
            elif option == 'max_y':
46 55
                retParameters['max_y'] = int(arg)
56
            elif option == 'velocity':
57
                retParameters['velocity'] = arg
58
                min_v, max_v = self.getVelocity(arg)
59
                retParameters['min_velocity'] = min_v
60
                retParameters['max_velocity'] = max_v
47 61
            elif option == 'nodes_number':
48 62
                retParameters['nodes_number'] = int(arg)
49 63
            elif option == 'max_velocity':
......
60 74
                retParameters['nodes_x_group'] = int(arg)
61 75
            elif option == 'groups_number':
62 76
                retParameters['groups_number'] = int(arg)
77
            elif option == 'aggregation':
78
                retParameters['aggregation'] = float(arg)
63 79
            else:
64 80
                print 'Unparsed ', option, '=', settings.get(sectionExp, option)
65 81
        return retParameters
66 82

  
67 83
    def configMobility(self, params):
68 84
        userMobi = params['mob_model']
69
        supportedModels = ["RandomWayPoint", "TimeVariantCommunity", "Milan"]
85
        supportedModels = ["RandomWayPoint",
86
                           "TimeVariantCommunity", "Milan", "ReferencePointGroup"]
70 87
        if userMobi not in supportedModels:
71 88
            print userMobi + " is not supported now!\n" \
72 89
                "This moility models are currently supported:"
......
88 105
            elif userMobi == "Milan":
89 106
                return milano_mob()
90 107

  
108
            elif userMobi == "ReferencePointGroup":
109
                # Reference Point Group model
110
                NxG = params['nodes_x_group']
111
                NG = params['groups_number']
112
                aggreg = params['aggregation']
113
                max_x, max_y = params['max_x'], params['max_y']
114
                min_v, max_v = params['min_velocity'], params['max_velocity']
115
                groups = [NxG for _ in range(NG)]
116
                nr_nodes = sum(groups)
117
                params['nodes_number'] = nr_nodes
118
                rpg = reference_point_group(
119
                    groups, velocity=(min_v, max_v), dimensions=(max_x, max_y), aggregation=aggreg)
120

  
121
                return rpg
91 122

  
92 123
            elif userMobi == "TimeVariantCommunity":
93 124
                '''
util/UnitDiskGraph.py
13 13
        self.nxG.add_nodes_from(range(len(points)))
14 14
        
15 15
        self.gtG = gt.Graph(directed=False)
16
        self.gtG.add_vertex(len(points))
16 17
        self.edge_weights = self.gtG.new_edge_property('float')
17 18
        self.gtG.edge_properties['weight'] = self.edge_weights        
18 19

  
......
43 44
        
44 45
        self.gtG.ep["weight"] = self.gtG.new_edge_property("float")
45 46
        eprops = [self.gtG.ep["weight"]]
46
        self.gtG.add_edge_list(edges, hashed=True, eprops=eprops)
47
        self.gtG.add_edge_list(edges, eprops=eprops)
47 48

  
48 49
    def getGraph(self):
49 50
        return self.gtG, self.nxG

Also available in: Unified diff