Statistics
| Branch: | Revision:

root / fiddle / simulation_analysis / plot_experiment_result.py @ e066fa74

History | View | Annotate | Download (5.68 KB)

1 4ceb9f92 Quynh PX Nguyen
#!/usr/bin/env python
2
3
"""
4
Input: *.plotdata
5
Output: a graph showing the average of BC and HBC
6
"""
7
import argparse
8
import os
9
import numpy as np
10
import matplotlib.pyplot as plt
11 e066fa74 Quynh PX Nguyen
import matplotlib.axes as axes
12
from pdb import set_trace as debugger
13 4ceb9f92 Quynh PX Nguyen
14
class ExperimentVisualizer():
15
    graph_descriptions = {
16 e066fa74 Quynh PX Nguyen
        "CN": "Synthetic Community Network",
17
        "CNR": "Real Community Network",
18 4ceb9f92 Quynh PX Nguyen
        "ER": "Erdos",
19 e066fa74 Quynh PX Nguyen
        "PL": "Power Law",
20
        "FG": "FFG",
21
        "FW": "FFW",
22
        "NN": "Ninux",
23
    }
24
25
    devices = {
26
        "r": "Router",
27
        "s": "Computer",
28
    }
29
30
    chart_types = {
31
        "line": "plot_line_chart",
32
        "bar": "plot_bar_chart",
33
        "speedup": "plot_speed_up_ratio",
34 4ceb9f92 Quynh PX Nguyen
    }
35
36
    def __init__(self):
37
        self.args = None
38 e066fa74 Quynh PX Nguyen
        self.graph_type = None # will be deduced by the filename
39 4ceb9f92 Quynh PX Nguyen
40
    def parse_args(self):
41
        parser = argparse.ArgumentParser(description="Plotting the comparison  \
42
                                         between Brandes Betweenness Centrality \
43 e066fa74 Quynh PX Nguyen
                                         (BBC) and Heuristic BC (HBC)")
44 4ceb9f92 Quynh PX Nguyen
        parser.add_argument("-i", dest="input")
45
        parser.add_argument("-o", dest="output", required=False,
46
                            default="")
47 e066fa74 Quynh PX Nguyen
        parser.add_argument("-c", dest="charttype", required=True,
48
                            choices=self.chart_types.keys()),
49
        parser.add_argument("-d", dest="device", required=False,
50
                            default="s", choices=self.devices.keys())
51 4ceb9f92 Quynh PX Nguyen
52
        self.args = parser.parse_args()
53
54
    def plot(self):
55
        input_dir = os.path.dirname(self.args.input)
56
        filename = os.path.splitext(os.path.basename(self.args.input))[0]
57
58 e066fa74 Quynh PX Nguyen
        self.graph_type = self.graph_descriptions.get(filename[0:2], "")
59 4ceb9f92 Quynh PX Nguyen
60
        if self.args.output == "":
61
            self.args.output = '%s/%s_BC_HBC.png' % (input_dir, filename)
62
63
        plot_data = self.read_plot_data()
64
65
        # Plot
66 e066fa74 Quynh PX Nguyen
        plot_function = getattr(self, self.chart_types[self.args.charttype])
67
        print '\n%s\n' % self.args.input
68
        plot_function(plot_data)
69
70 4ceb9f92 Quynh PX Nguyen
71
    def read_plot_data(self):
72
        plot_data = np.loadtxt(self.args.input,
73
            dtype= {
74 e066fa74 Quynh PX Nguyen
                'names': ('filename', 'typotype', 'graphtype', 'numofnodes', 'avg_bc', 'avg_hbc',
75 4ceb9f92 Quynh PX Nguyen
                          'std_bc', 'std_hbc'),
76 e066fa74 Quynh PX Nguyen
                'formats': ('a40', 'a10', 'a2', 'i4', 'f8', 'f8', 'f8', 'f8')
77 4ceb9f92 Quynh PX Nguyen
            },
78
            delimiter=','
79
        )
80 e066fa74 Quynh PX Nguyen
81 4ceb9f92 Quynh PX Nguyen
        plot_data = plot_data[plot_data['numofnodes'].argsort()]
82
        return plot_data
83
84
85 e066fa74 Quynh PX Nguyen
    def plot_speed_up_ratio(self, plot_data):
86
        if plot_data['graphtype'][0] in ['NN', 'FG', 'FW']:
87
            xlabel = [self.graph_descriptions[term] for term in plot_data['graphtype']]
88
            self.graph_type = self.graph_descriptions["CNR"]
89
            x = [1, 2, 3]
90
        else:
91
            x = plot_data['numofnodes']
92
            xlabel = x
93
        ys = list()
94
        ys.append(plot_data['avg_bc'] / plot_data['avg_hbc'])
95
        ys.append(plot_data['avg_bc'] / plot_data['avg_bc'])
96
97
        colors = ['r', 'b']
98
        markers = ['^', 'o']
99
        labels= ['HBC', 'BBC']
100
        size = 100
101
        fontsize = 18
102
        for index, y in enumerate(ys):
103
            plt.scatter(x, y, c=colors[index], marker=markers[index], s=size, label=labels[index])
104
            plt.xticks(x, xlabel)
105
            ymin = plt.gca().get_ylim()[0]
106
            if ymin < 0:
107
                plt.ylim(ymin=0)
108
        plt.tick_params(axis='both', which='major', labelsize=fontsize)
109
        plt.title("%s on %s" % (self.graph_type, self.devices[self.args.device]), fontsize=fontsize)
110
        plt.legend(bbox_to_anchor=(1, 0.8))
111
        plt.ylabel("Speed-up ratio", fontsize=fontsize)
112
113
        if self.graph_type != self.graph_descriptions["CNR"]:
114
            plt.xlabel("# of nodes", fontsize=fontsize)
115
        plt.savefig(self.args.output)
116
        print "Finish plotting %s" % self.args.output
117
        plt.close()
118
119
120
    def plot_line_chart(self, plot_data):
121 4ceb9f92 Quynh PX Nguyen
        x = plot_data['numofnodes']
122 e066fa74 Quynh PX Nguyen
        print 'num of nodes: %s' % x
123 4ceb9f92 Quynh PX Nguyen
        y1 = plot_data['avg_bc']
124
        y2 = plot_data['avg_hbc']
125
126 e066fa74 Quynh PX Nguyen
        plt.plot(x, y1, marker='o', linestyle='-', color='b', label='BBC')
127
        plt.plot(x, y2, marker='^', linestyle='--', color='r', label='HBC')
128
129
        fontsize = 18
130
        plt.tick_params(axis='both', which='major', labelsize=fontsize)
131
        plt.title("%s on %s" % (self.graph_type, self.devices[self.args.device]), fontsize=fontsize)
132
        plt.legend(bbox_to_anchor=(0.25, 1))
133
        plt.xlabel("# of nodes", fontsize=fontsize)
134
        plt.ylabel("Running time (secs)", fontsize=fontsize)
135
        plt.savefig(self.args.output)
136
        print "Finish plotting %s" % self.args.output
137
        plt.close()
138
139
    def plot_bar_chart(self, plot_data):
140
        x = [self.graph_descriptions[i] for i in plot_data['graphtype']]
141
        bc = plot_data['avg_bc']
142
        hbc = plot_data['avg_hbc']
143
144
        bc_std = plot_data['std_bc']
145
        hbc_std = plot_data['std_hbc']
146
147
        N = len(bc_std)
148
        ind = np.arange(N)
149
        width = 0.35
150
        fontsize = 18
151
152
        p1 = plt.bar(ind, bc, width, color='b', yerr=bc_std)
153
        p2 = plt.bar(ind + 0.35, hbc, width, color='r', yerr=hbc_std)
154
        plt.xticks(ind + width, x)
155
        plt.ylabel("Running time (secs)", fontsize=fontsize)
156
        plt.legend((p1[0], p2[0]), ('BBC', 'HBC'))
157
158
        title = "Real community networks on %s" % self.devices[self.args.device]
159
        plt.title(title, fontsize=fontsize)
160
        plt.tick_params(axis='both', which='major', labelsize=fontsize)
161 4ceb9f92 Quynh PX Nguyen
        plt.savefig(self.args.output)
162 e066fa74 Quynh PX Nguyen
        print "Finish plotting %s" % self.args.output
163 4ceb9f92 Quynh PX Nguyen
        plt.close()
164
165
166
if __name__ == '__main__':
167
    vis = ExperimentVisualizer()
168
    vis.parse_args()
169
    vis.plot()