Statistics
| Branch: | Revision:

mobicen / simulator.py @ c16015e2

History | View | Annotate | Download (3.63 KB)

1 dfc44250 LoreBz
import graph_tool.centrality as gtc
2 fa4a0a42 LoreBz
import warnings
3 e1cf8bea LoreBz
import util.EventScheduler as ES
4
from tqdm import tqdm  # https://pypi.org/project/tqdm/#usage
5
from util.UnitDiskGraph import UnitDiskGraph
6
from util.ConfPars import ConfSettings
7 fa4a0a42 LoreBz
import pandas as pd
8 dfc44250 LoreBz
from multiprocessing import Pool
9 e1cf8bea LoreBz
10
import random
11
import code  # code.interact(local=dict(globals(), **locals()))
12
13
import networkx as nx
14
import util.MyUtil as myu
15 1ef4948a LoreBz
import util.nx2gt as nx2gt
16 e1cf8bea LoreBz
from time import sleep
17 fa4a0a42 LoreBz
import matplotlib.pyplot as plt
18
plt.ion()
19 e1cf8bea LoreBz
20
21 dfc44250 LoreBz
def f(params):
22
    pos, radius = params['pos'], params['radius']
23
    # Build new UnitDiskGraph
24
    G, nxG = UnitDiskGraph(pos, radius).getGraph()
25
    params['nxG'] = nxG
26
    ws = G.edge_properties["weight"]
27
    vp, ep = gtc.betweenness(G, norm=False, weight=ws)
28
    btwd = {i: vp.a[i] for i in range(len(vp.a))}
29
    params['btw'] = btwd
30
    return params
31
32
33 e1cf8bea LoreBz
class Simulator(object):
34
35 dfc44250 LoreBz
    def __init__(self, settingsFile, sectionExp, outPath, num_workers=1, gui=False):
36 e1cf8bea LoreBz
        self.gui = gui
37 dfc44250 LoreBz
        self.num_workers = num_workers
38 e1cf8bea LoreBz
        self.sched = ES.EventScheduler()  # scheduler
39
        config = ConfSettings(settingsFile, sectionExp)
40
        self.params = config.getSimulationParameters()
41
        self.expName = sectionExp
42
        self.mob = config.configMobility(self.params)
43 fa4a0a42 LoreBz
        self.OP = outPath
44 2dbcade9 LoreBz
        NN = self.params['nodes_number']
45
        self.statsFiles = {}
46
        for i in range(NN):
47 c16015e2 LoreBz
            f = open(outPath+"/stats"+'%08d' % i+".csv", 'a+')
48 2dbcade9 LoreBz
            self.statsFiles[i] = f
49
            f.write("Time,BC\n")
50 e1cf8bea LoreBz
51 dfc44250 LoreBz
    def batch_tasks(self, sched, mobi, num_workers=5):
52
        # prepare next num_workers tasks
53
        tasks = []
54
        for i in range(num_workers):
55
            event = sched.pop_event()
56
            # Get new coordinates
57
            positions = next(mobi)
58
            tasks.append({'pos': positions, 'radius': self.params['radius'], 'time': sched.elapsed_time(
59
            ), 'tag': sched.processed_events()})
60
            # schedule next DV
61
            jitter = [-1, 1][random.randrange(2)]*random.uniform(0, 0.866)
62
            sched.schedule_event(1.0 + jitter, "move!")
63
64
        p = Pool(num_workers)
65
        res = p.map(f, tasks)
66
        p.close()
67
        return res
68
69 e1cf8bea LoreBz
    def runSimulation(self):
70 fa4a0a42 LoreBz
        warnings.filterwarnings("ignore", module="matplotlib")
71
        sched = self.sched
72 e1cf8bea LoreBz
        self.sched.schedule_event(0, "move!")
73
74
        print "\nRunning " + self.expName + "..."
75
        with tqdm(total=self.params['duration']) as pbar:
76 dfc44250 LoreBz
            while(sched.processed_events() < self.params['duration']):
77
                prev = sched.processed_events()
78
                # Process a batch of tasks
79
                results = self.batch_tasks(
80
                    self.sched, self.mob, num_workers=self.num_workers)
81
                current = sched.processed_events()
82
                pbar.update(current-prev)
83
84
                #code.interact(local=dict(globals(), **locals()))
85
                # Log results to disk
86
                for res in results:
87
                    self.logBTW(res['btw'], res['tag'])
88
89
                #code.interact(local=dict(globals(), **locals()))
90
                if self.gui and self.num_workers == 1:
91
                    res = results[0]
92
                    self.draw(res['nxG'], res['pos'], res['btw'])
93 e1cf8bea LoreBz
94 2dbcade9 LoreBz
        # Main Loop End Here
95
        for f in self.statsFiles:
96
            self.statsFiles[f].close()
97 e1cf8bea LoreBz
        return
98
99 dfc44250 LoreBz
    def logBTW(self, btw, tag):
100 fa4a0a42 LoreBz
        tag = '%08d' % tag
101 dfc44250 LoreBz
        for n, bc in btw.items():
102
            self.statsFiles[n].write(tag+","+str(bc)+"\n")
103 fa4a0a42 LoreBz
104 2dbcade9 LoreBz
    def draw(self, G, pos, measures=None):
105 fa4a0a42 LoreBz
        xmax = self.params['max_x']
106
        ymax = self.params['max_y']
107 2dbcade9 LoreBz
        myu.draw(G, pos, xmax, ymax, measures)