Revision dfc44250

View differences:

mobiExp.py
13 13
    sectionExp = ''
14 14
    outPath = ''
15 15
    cdir = ''
16
    num_workers = 1
16 17
    gui = False
17 18
    options, remainder = getopt.getopt(
18
        sys.argv[1:], '', ['sf=', 'en=', 'out=', 'gui'])
19
        sys.argv[1:], '', ['sf=', 'en=', 'out=', 'thr=', 'gui'])
19 20
    mand = set(['--sf', '--en', '--out'])
20 21
    opts = [x[0] for x in options]
21 22
    # print 'OPTIONS   :', opts
......
28 29
            settingsFile = arg
29 30
        if opt in ('--en'):
30 31
            sectionExp = arg
32
        if opt in ('--thr'):
33
            num_workers = int(arg)
31 34
        if opt in ('--out'):
32 35
            outPath = arg
33 36
            outPath.rstrip("/")
......
43 46
        if opt in ('--gui'):
44 47
            gui = True
45 48

  
46
    sim = Simulator(settingsFile, sectionExp, cdir, gui)
49
    sim = Simulator(settingsFile, sectionExp, cdir, num_workers=num_workers, gui=gui)
47 50
    print "Simulation Parameters\n"
48 51
    pprint(sim.params)
49 52
    #code.interact(local=dict(globals(), **locals()))
settings.ini
51 51
radius = 30.0
52 52

  
53 53
# 50 nodi
54
[rwpR30N50:baseRWP]
54
[rwpR30N50.0:baseRWP]
55 55
nodes_number = 50
56 56
radius = 30.0
57 57

  
simulator.py
1
import graph_tool.centrality as gtc
1 2
import warnings
2 3
import util.EventScheduler as ES
3 4
from tqdm import tqdm  # https://pypi.org/project/tqdm/#usage
4 5
from util.UnitDiskGraph import UnitDiskGraph
5 6
from util.ConfPars import ConfSettings
6 7
import pandas as pd
8
from multiprocessing import Pool
7 9

  
8 10
import random
9 11
import code  # code.interact(local=dict(globals(), **locals()))
......
16 18
plt.ion()
17 19

  
18 20

  
21
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

  
19 33
class Simulator(object):
20 34

  
21
    def __init__(self, settingsFile, sectionExp, outPath, gui):
35
    def __init__(self, settingsFile, sectionExp, outPath, num_workers=1, gui=False):
22 36
        self.gui = gui
37
        self.num_workers = num_workers
23 38
        self.sched = ES.EventScheduler()  # scheduler
24 39
        config = ConfSettings(settingsFile, sectionExp)
25 40
        self.params = config.getSimulationParameters()
......
33 48
            self.statsFiles[i] = f
34 49
            f.write("Time,BC\n")
35 50

  
51
    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

  
36 69
    def runSimulation(self):
37 70
        warnings.filterwarnings("ignore", module="matplotlib")
38 71
        sched = self.sched
......
40 73

  
41 74
        print "\nRunning " + self.expName + "..."
42 75
        with tqdm(total=self.params['duration']) as pbar:
43
            while(sched.elapsed_time() < self.params['duration']):
44
                pbar.update(sched.step())
45
                event = sched.pop_event()
46

  
47
                # Get new coordinates
48
                positions = next(self.mob)
49

  
50
                # Build new UnitDiskGraph
51
                G, nxG = UnitDiskGraph(positions, self.params['radius']).getGraph()
52

  
53
                #stats = ['BC', 'LC', 'DEG']
54
                stats = ['BC']
55
                btw = self.logStatistics(G, stats, sched.processed_events())
56
              
57
                if self.gui:
58
                    btwd= {i:btw[i] for i in range(len(btw))}
59
                    self.draw(nxG, positions, measures=btwd)
60
                
61
                # schedule next DV
62
                jitter = [-1, 1][random.randrange(2)]*random.uniform(0, 0.866)
63
                sched.schedule_event(1.0 + jitter, "move!")
76
            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'])
64 93

  
65 94
        # Main Loop End Here
66 95
        for f in self.statsFiles:
67 96
            self.statsFiles[f].close()
68 97
        return
69 98

  
70
    def logStatistics(self, G, whatLog, tag):
99
    def logBTW(self, btw, tag):
71 100
        tag = '%08d' % tag
72
        for stat in whatLog:
73
            if stat == 'BC':
74
                import graph_tool.centrality as gtc
75
                ws = G.edge_properties["weight"]
76
                vp, ep = gtc.betweenness(G, norm=False, weight=ws)
77
                for i in range(len(vp.a)):
78
                    self.statsFiles[i].write(tag+","+str(vp.a[i])+"\n")
79

  
80
                '''bw_centrality = nx.betweenness_centrality(G, normalized=False,  weight='weight', endpoints=True)
81
                #print "Convertig nxG to graph_tool Graph..."
82
                #gtG = nx2gt.nx2gt(G)
83
                #print "Computing BC with graph_tool..."
84
                #btwl = G.betweenness(directed=False, weights="weight")
85
                #print "Writing BC to disk..."
86
                btw = {i: vp.a[i] for i in range(len(vp.a))}
87
                df = pd.DataFrame(btw.items(), columns=['Node', 'BC'])
88
                df.to_csv(self.OP+"/BC"+tag+".csv", sep=',',
89
                          encoding='utf-8', index=False)'''
90
            '''if stat == 'LC':
91
                load_indexes = nx.load_centrality(
92
                    G, normalized=False, weight='weight')
93
                df = pd.DataFrame(load_indexes.items(), columns=['Node', 'LC'])
94
                df.to_csv(self.OP+"/LC"+tag+".csv", sep=',',
95
                          encoding='utf-8', index=False)
96
            if stat == 'DEG':
97
                degrees = dict(G.degree())
98
                df = pd.DataFrame(degrees.items(), columns=['Node', 'DEG'])
99
                df.to_csv(self.OP+"/DEG"+tag+".csv", sep=',',
100
                          encoding='utf-8', index=False)'''
101
        return vp.a
101
        for n, bc in btw.items():
102
            self.statsFiles[n].write(tag+","+str(bc)+"\n")
102 103

  
103 104
    def draw(self, G, pos, measures=None):
104 105
        xmax = self.params['max_x']

Also available in: Unified diff