Statistics
| Branch: | Revision:

mobicen / simulator.py @ 27b1b922

History | View | Annotate | Download (3.47 KB)

1
import warnings
2
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
import pandas as pd
7

    
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
import util.nx2gt as nx2gt
14
from time import sleep
15
import matplotlib.pyplot as plt
16
plt.ion()
17

    
18

    
19
class Simulator(object):
20

    
21
    def __init__(self, settingsFile, sectionExp, outPath, gui):
22
        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
        self.OP = outPath
29

    
30
    def runSimulation(self):
31
        warnings.filterwarnings("ignore", module="matplotlib")
32
        sched = self.sched
33
        self.sched.schedule_event(0, "move!")
34

    
35
        print "\nRunning " + self.expName + "..."
36
        with tqdm(total=self.params['duration']) as pbar:
37
            while(sched.elapsed_time() < self.params['duration']):
38
                pbar.update(sched.step())
39
                event = sched.pop_event()
40

    
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
                    self.draw(G, positions)
49
                #stats = ['BC', 'LC', 'DEG']
50
                stats = ['BC']
51

    
52
                self.logStatistics(G, stats, sched.processed_events())
53
                # schedule next DV
54
                jitter = [-1, 1][random.randrange(2)]*random.uniform(0, 0.866)
55
                sched.schedule_event(1.0 + jitter, "move!")
56

    
57
        return
58

    
59
    def logStatistics(self, G, whatLog, tag):
60
        tag = '%08d' % tag
61
        for stat in whatLog:
62
            if stat == 'BC':
63
                '''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
                #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
                btw = {i: vp.a[i] for i in range(len(vp.a))}
73
                df = pd.DataFrame(btw.items(), columns=['Node', 'BC'])
74
                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)