Statistics
| Branch: | Revision:

mobicen / simulator.py @ 23c7ab1e

History | View | Annotate | Download (4 KB)

1
import graph_tool.all as gt
2
import warnings
3
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
import pandas as pd
8
from multiprocessing import Pool
9

    
10
import random
11
import code  # code.interact(local=dict(globals(), **locals()))
12
from pprint import pprint
13
import networkx as nx
14
import util.MyUtil as myu
15
from time import sleep
16
import matplotlib.pyplot as plt
17
plt.ion()
18

    
19

    
20
def f(params):
21
    pos, radius = params['pos'], params['radius']
22
    # Build new UnitDiskGraph
23
    G, nxG = UnitDiskGraph(pos, radius).getGraph()
24
    params['gtG'] = G
25
    params['nxG'] = nxG
26
    ws = G.edge_properties["weight"]
27
    vp, ep = gt.betweenness(G, norm=False, weight=ws)
28
    btwd = {i: vp.a[i] for i in range(len(vp.a))}
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
36
    return params
37

    
38

    
39
class Simulator(object):
40

    
41
    def __init__(self, settingsFile, sectionExp, outPath, num_workers=1, gui=False):
42
        self.gui = gui
43
        self.num_workers = num_workers
44
        self.sched = ES.EventScheduler()  # scheduler
45
        config = ConfSettings(settingsFile, sectionExp)
46
        self.params = config.getSimulationParameters()
47
        self.expName = sectionExp
48
        self.mob = config.configMobility(self.params)
49
        self.OP = outPath
50
        NN = self.params['nodes_number']
51
        self.statsFiles = {}
52
        for i in range(NN):
53
            f = open(outPath+"/stats"+'%08d' % i+".csv", 'a+')
54
            self.statsFiles[i] = f
55
            f.write("Time,BC,DEG,KCORE\n")
56

    
57
    def batch_tasks(self, sched, mobi, num_workers=5):
58
        # prepare next num_workers tasks
59
        tasks = []
60
        for i in range(num_workers):
61
            event = sched.pop_event()
62
            # Get new coordinates
63
            positions = next(mobi)
64
            tasks.append({'pos': positions, 'radius': self.params['radius'], 'time': sched.elapsed_time(
65
            ), 'tag': sched.processed_events()})
66
            # schedule next DV
67
            jitter = [-1, 1][random.randrange(2)]*random.uniform(0, 0.866)
68
            sched.schedule_event(1.0 + jitter, "move!")
69

    
70
        p = Pool(num_workers)
71
        res = p.map(f, tasks)
72
        p.close()
73
        return res
74

    
75
    def runSimulation(self):
76
        warnings.filterwarnings("ignore", module="matplotlib")
77
        sched = self.sched
78
        self.sched.schedule_event(0, "move!")
79

    
80
        print "\nRunning " + self.expName + "..."
81
        with tqdm(total=self.params['duration']) as pbar:
82
            while(sched.processed_events() < self.params['duration']):
83
                prev = sched.processed_events()
84
                # Process a batch of tasks
85
                results = self.batch_tasks(
86
                    self.sched, self.mob, num_workers=self.num_workers)
87
                current = sched.processed_events()
88
                pbar.update(current-prev)
89

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

    
95
                if self.gui and self.num_workers == 1:
96
                    res = results[0]
97
                    self.draw(res['nxG'], res['pos'], res['btw'])
98

    
99
        # Main Loop End Here
100
        for f in self.statsFiles:
101
            self.statsFiles[f].close()
102
        return
103

    
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")
112

    
113
    def draw(self, G, pos, measures=None):
114
        xmax = self.params['max_x']
115
        ymax = self.params['max_y']
116
        myu.draw(G, pos, xmax, ymax, measures)