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