]> git.donarmstrong.com Git - neurodebian.git/blob - survey/makestats
And again.
[neurodebian.git] / survey / makestats
1 #!/usr/bin/python
2
3 from glob import glob
4 import json
5 import sys
6 import pylab as pl
7 import numpy as np
8 import time
9 from mvpa.misc.plot.base import plot_bars
10
11 # uniform colors for OS results
12 os_colors = ['#B63537', '#4E4DA0', '#008200', 'gray']
13 os_order = ['linux', 'mac', 'win', 'otheros']
14 # resources
15 resource_categories = {
16     'vendor': 'Vendor/Project website',
17     'retailer': 'Retailer',
18     'os': 'Operating system',
19     'cpan': 'CPAN',
20     'cran': 'CRAN',
21     'epel': 'EPEL',
22     'fink': 'Fink',
23     'freebsdports': 'FreeBSD ports',
24     'incf': 'INCF',
25     'macports': 'Macports',
26     'matlabcentral': 'Matlab Central',
27     'neurodebian': 'NeuroDebian',
28     'nitrc': 'NITRC',
29     'pypi': 'PyPi',
30     'pythonbundles': 'Python bundles',
31     'sourceforge': 'Sourceforge',
32     'other': 'Other resource'
33     }
34 # software categories
35 sw_categories = {
36         'general': 'General computing',
37         'dc': 'Distributed computing',
38         'img': 'Brain imaging',
39         'datamanage': 'Data management',
40         'neusys': 'Neural systems modeling',
41         'electro': 'Electrophysiology, MEG/EEG',
42         'bci': 'Brain-computer interface',
43         'acq': 'Hardware interface/Data acquisition',
44         'rt': 'Real-time solutions',
45         'psychophys': 'Psychophysics/Experiment control'
46         }
47
48 # some meaningful groups of OSes
49 redhat_family = ["rhel", "centos", "fedora", "scilinux"]
50 debian_family = ["debian", "ubuntu", "biolinux"]
51 suse_family = ["suse", "slel"]
52 other_linux_family = ["gentoo", "mandriva", "arch", "slackware", "otherlinux"]
53 other_family = ["starbsd", "unix", "qnx", "beos", "solaris", "other"]
54
55 os_cat_names = {
56         'win': 'Windows',
57         'mac': 'Mac OS',
58         'linux': 'GNU/Linux',
59         'otheros': 'Other OS'
60         }
61
62 os_family = {
63         'win': ["windows"],
64         'mac': ["macosx"],
65         'linux': redhat_family + debian_family + suse_family + other_linux_family,
66         'otheros': other_family
67         }
68 # end the reverse mapping
69 os_family_rev = {}
70 for ost in os_family:
71     for os in os_family[ost]:
72         os_family_rev[os] = ost
73
74
75 def load_list2dict(name):
76     d = {}
77     lfile = open(name)
78     for line in lfile:
79         kv = line.split(':')
80         d[kv[0]] = kv[1].strip().strip('"')
81     return d
82
83
84
85 class DB(dict):
86     os_dict = load_list2dict('oslist.txt')
87     datamod_dict = load_list2dict('datamodlist.txt')
88     sw_dict = load_list2dict('swlist.txt')
89
90     def __init__(self, srcdir):
91         # eats the whole directory
92         if srcdir is None:
93             return
94         datafilenames = glob('%s/*.json' % srcdir)
95         for dfn in datafilenames:
96             rawdata = json.load(open(dfn))
97             self[rawdata['timestamp']] = rawdata
98
99     def get_unique(self, key):
100         # return a set of all (unique) values for a field id
101         uniq = set()
102         for d in self.values():
103             if key in d:
104                 el = d[key]
105                 if isinstance(el, list):
106                     uniq = uniq.union(el)
107                 else:
108                     uniq = uniq.union((el,))
109         return uniq
110
111     def get_not_none(self, key):
112         # return a list of all values of a specific field id
113         # the second return value is count of submission that did not have data
114         # for this field id
115         val = []
116         missing = 0
117         for d in self.values():
118             if key in d:
119                 el = d[key]
120                 if isinstance(el, list):
121                     val.extend(el)
122                 else:
123                     if el == 'none':
124                         missing += 1
125                     else:
126                         val.append(el)
127             else:
128                 missing += 1
129         return val, missing
130
131     def get_counts(self, key):
132         # return a dict with field values as keys and respective submission 
133         # count as value
134         vals = self.get_not_none(key)[0]
135         uniq = np.unique(vals)
136         counts = dict(zip(uniq, [vals.count(u) for u in uniq]))
137         return counts
138
139     def select_match(self, key, values):
140         # return a db with all submissions were a field id has one of the
141         # supplied values
142         match = DB(None)
143         for k, v in self.items():
144             if not key in v:
145                 continue
146             el = v[key]
147             if isinstance(el, list):
148                 if len(set(values).intersection(el)):
149                     match[k] = v
150             elif el in values:
151                 match[k] = v
152         return match
153
154     def get_nice_name(self, id):
155         srcs = [DB.os_dict, os_cat_names, DB.sw_dict, sw_categories,
156                 resource_categories]
157         for src in srcs:
158             if id in src:
159                 return src[id]
160         # not found, nothing nicer
161         return id
162
163
164 def mkpic_os_per_env(db, destdir):
165     envs = ['pers_os', 'man_os', 'virt_host_os', 'virt_guest_os']
166     env_names = ['Personal', 'Managed', 'Virt. Host', 'Virt. Guest']
167     env_stats = {}
168     offset = 0
169     for env in envs:
170         counts = db.get_counts(env)
171         stats = dict(zip(os_family.keys(), [0] * len(os_family)))
172         for os in counts:
173             stats[os_family_rev[os]] += counts[os]
174         total_count = np.sum(stats.values())
175         for osf in stats:
176             stats[osf] = float(stats[osf]) / total_count
177         env_stats[env] = stats
178     # make stacked barplot
179     pl.figure(figsize=(6.4, 4.8), facecolor='w', edgecolor='k')
180     x = np.arange(len(envs))
181     bottoms = np.zeros(len(envs))
182     for i, os in enumerate(os_order):
183         stat = [env_stats[e][os] for e in envs]
184         pl.bar(x, stat, bottom=bottoms, color=os_colors[i],
185                label=db.get_nice_name(os), width=0.8)
186         bottoms += stat
187     pl.legend(loc='lower right')
188     pl.xticks(x + 0.4,  [db.get_nice_name(e) for e in env_names])
189     pl.xlim(-0.25, len(envs))
190     pl.title("Operating system preference by environment")
191     pl.ylabel("Fraction of submissions")
192     pl.savefig('%s/ospref_by_env.png' % destdir, format='png', dpi=80)
193
194 def mkpic_submissions_per_datamod(db, destdir):
195     # simple demo
196     spd = db.get_counts('bg_datamod')
197     spd = sorted(spd.items(), cmp=lambda x, y: cmp(x[1], y[1]))[::-1]
198     x = np.arange(len(spd))
199     pl.figure(figsize=(6.4, 4.8), facecolor='w', edgecolor='k')
200     pl.title('Submissions per data modality')
201     pl.bar(x, [s[1] for s in spd])
202     pl.xticks(x + 0.5,  [db.datamod_dict[k[0]] for k in spd], rotation=-10)
203     pl.ylabel('Survey submissions per data modality\n(multiple choices per submission possible)')
204     pl.savefig('%s/submissions_per_datamod.png' % destdir, format='png', dpi=80)
205
206 def mkpic_resources(db, destdir):
207     res = db.get_counts('software_resource')
208     res = res.items()
209     x = np.arange(len(res))
210     pl.figure(figsize=(6.4, 4.8), facecolor='w', edgecolor='k')
211     pl.title('Software resources')
212     pl.bar(x + (1./8), [s[1] for s in res], width=0.75, color = '#008200')
213     pl.xticks(x + 0.5,  ['' for s in res])
214     for i, s in enumerate(res):
215         pl.text(i+.5, 0.1, db.get_nice_name(s[0]), rotation=90,
216                 horizontalalignment='center',
217                 verticalalignment='bottom',
218                 bbox=dict(facecolor='white', alpha=0.8, edgecolor='white',
219                           color='white'))
220     pl.ylabel('Number of submissions')
221     pl.savefig('%s/software_resources.png' % destdir, format='png', dpi=80)
222
223 def mkpic_software(db, destdir):
224     for typ in sw_categories.keys():
225         counts = db.get_counts('sw_%s' % typ)
226         pl.figure(figsize=(6.4, 4.8), facecolor='w', edgecolor='k')
227         pl.title("Software popularity: %s" % db.get_nice_name(typ))
228         if not len(counts):
229             pl.text(.5, .5, "[Insufficient data for this figure]",
230                     horizontalalignment='center')
231             pl.axis('off')
232         else:
233             # sort by name
234             stats = sorted(counts.items(), cmp=lambda x, y: cmp(x[0], y[0]))
235             x = np.arange(len(stats))
236             pl.bar(x + (1./8), [s[1] for s in stats], width=0.75, color = '#008200')
237             pl.xticks(x + 0.5,  ['' for s in stats])
238             for i, s in enumerate(stats):
239                 pl.text(i+.5, 0.1, db.get_nice_name(s[0]), rotation=90,
240                         horizontalalignment='center',
241                         verticalalignment='bottom',
242                         bbox=dict(facecolor='white', alpha=0.8, edgecolor='white',
243                                   color='white'))
244             pl.xlim(0, len(stats))
245             pl.ylabel("Number of submissions")
246         pl.savefig('%s/sw_%s.png' % (destdir, typ), format='png', dpi=80)
247
248 def mkpic_rating_by_os(db, env, items, destdir, title):
249     pl.figure(figsize=(6.4, 4.8), facecolor='w', edgecolor='k')
250     for i, os in enumerate(os_order):
251         ratings = [db.select_match(env,
252                         os_family[os]).get_not_none('%s' % (it,))[0]
253                             for it in items]
254         plot_bars(ratings, offset=((i+1)*0.2)-0.1, color=os_colors[i],
255                   title=title, ylabel="Mean rating", label=db.get_nice_name(os))
256     pl.ylim((0,3))
257     pl.xlim((0,len(items)))
258     pl.yticks((0, 3), ['Disagree', 'Agree'], rotation=90)
259     pl.xticks(np.arange(len(items))+0.5, [i[-2:] for i in items],
260               horizontalalignment='center')
261     pl.legend(loc='lower right')
262     pl.savefig('%s/ratings_%s.png' % (destdir, env), format='png', dpi=80)
263
264
265 def main(srcdir, destdir):
266     db = DB(srcdir)
267     for pic in [mkpic_submissions_per_datamod, mkpic_os_per_env, mkpic_software,
268                 mkpic_resources]:
269         pic(db, destdir)
270     mkpic_rating_by_os(db, 'pers_os', ['pers_r%i' % i for i in range(1, 9)], destdir,
271                        "Ratings: Personal environment")
272     mkpic_rating_by_os(db, 'man_os', ['man_r%i' % i for i in range(1, 5)], destdir,
273                        "Ratings: Managed environment")
274     mkpic_rating_by_os(db, 'virt_host_os', ['virt_r%i' % i for i in range(1, 4)], destdir,
275                        "Ratings: Virtual environment (by host OS)")
276     # submission stats: this is RST
277     statsfile = open('%s/stats.txt' % destdir, 'w')
278     statsfile.write('::\n\n  Number of submissions: %i\n' % len(db))
279     statsfile.write('  Statistics last updated: %s\n\n' \
280             % time.strftime('%A, %B %d %Y, %H:%M:%S UTC', time.gmtime()))
281     statsfile.close()
282
283 if __name__ == '__main__':
284     main(sys.argv[1], sys.argv[2])