Statistics
| Branch: | Revision:

mobicen / simulator.py @ 27b1b922

History | View | Annotate | Download (3.47 KB)

1 fa4a0a42 LoreBz
import warnings
2 e1cf8bea LoreBz
import util.EventScheduler as ES
3
from tqdm import tqdm  # https://pypi.org/project/tqdm/#usage
4
from util.UnitDiskGraph import UnitDiskGraph
5
from util.ConfPars import ConfSettings
6 fa4a0a42 LoreBz
import pandas as pd
7 e1cf8bea LoreBz
8
import random
9
import code  # code.interact(local=dict(globals(), **locals()))
10
11
import networkx as nx
12
import util.MyUtil as myu
13 1ef4948a LoreBz
import util.nx2gt as nx2gt
14 e1cf8bea LoreBz
from time import sleep
15 fa4a0a42 LoreBz
import matplotlib.pyplot as plt
16
plt.ion()
17 e1cf8bea LoreBz
18
19
class Simulator(object):
20
21 fa4a0a42 LoreBz
    def __init__(self, settingsFile, sectionExp, outPath, gui):
22 e1cf8bea LoreBz
        self.gui = gui
23
        self.sched = ES.EventScheduler()  # scheduler
24
        config = ConfSettings(settingsFile, sectionExp)
25
        self.params = config.getSimulationParameters()
26
        self.expName = sectionExp
27
        self.mob = config.configMobility(self.params)
28 fa4a0a42 LoreBz
        self.OP = outPath
29 e1cf8bea LoreBz
30
    def runSimulation(self):
31 fa4a0a42 LoreBz
        warnings.filterwarnings("ignore", module="matplotlib")
32
        sched = self.sched
33 e1cf8bea LoreBz
        self.sched.schedule_event(0, "move!")
34
35
        print "\nRunning " + self.expName + "..."
36
        with tqdm(total=self.params['duration']) as pbar:
37 fa4a0a42 LoreBz
            while(sched.elapsed_time() < self.params['duration']):
38
                pbar.update(sched.step())
39
                event = sched.pop_event()
40 e1cf8bea LoreBz
41
                # Get new coordinates
42
                positions = next(self.mob)
43
44
                # Build new UnitDiskGraph
45
                G = UnitDiskGraph(positions, self.params['radius']).getGraph()
46
47
                if self.gui:
48 fa4a0a42 LoreBz
                    self.draw(G, positions)
49 1ef4948a LoreBz
                #stats = ['BC', 'LC', 'DEG']
50
                stats = ['BC']
51 fa4a0a42 LoreBz
52
                self.logStatistics(G, stats, sched.processed_events())
53 e1cf8bea LoreBz
                # schedule next DV
54
                jitter = [-1, 1][random.randrange(2)]*random.uniform(0, 0.866)
55 fa4a0a42 LoreBz
                sched.schedule_event(1.0 + jitter, "move!")
56 e1cf8bea LoreBz
57
        return
58
59 fa4a0a42 LoreBz
    def logStatistics(self, G, whatLog, tag):
60
        tag = '%08d' % tag
61
        for stat in whatLog:
62
            if stat == 'BC':
63 1ef4948a LoreBz
                '''bw_centrality = nx.betweenness_centrality(G, normalized=False,  weight='weight', endpoints=True)'''
64
                #code.interact(local=dict(globals(), **locals()))
65
                import graph_tool.centrality as gtc
66 27b1b922 LoreBz
                #print "Convertig nxG to graph_tool Graph..."
67
                #gtG = nx2gt.nx2gt(G)
68
                ws=G.edge_properties["weight"]
69
                #print "Computing BC with graph_tool..."
70
                vp, ep = gtc.betweenness(G, norm=False, weight=ws)
71
                #print "Writing BC to disk..."
72 1ef4948a LoreBz
                btw = {i: vp.a[i] for i in range(len(vp.a))}
73
                df = pd.DataFrame(btw.items(), columns=['Node', 'BC'])
74 fa4a0a42 LoreBz
                df.to_csv(self.OP+"/BC"+tag+".csv", sep=',',
75
                          encoding='utf-8', index=False)
76
            if stat == 'LC':
77
                load_indexes = nx.load_centrality(
78
                    G, normalized=False, weight='weight')
79
                df = pd.DataFrame(load_indexes.items(), columns=['Node', 'LC'])
80
                df.to_csv(self.OP+"/LC"+tag+".csv", sep=',',
81
                          encoding='utf-8', index=False)
82
            if stat == 'DEG':
83
                degrees = dict(G.degree())
84
                df = pd.DataFrame(degrees.items(), columns=['Node', 'DEG'])
85
                df.to_csv(self.OP+"/DEG"+tag+".csv", sep=',',
86
                          encoding='utf-8', index=False)
87
88
    def draw(self, G, pos):
89
        xmax = self.params['max_x']
90
        ymax = self.params['max_y']
91
        myu.draw(G, pos, xmax, ymax)