]> git.donarmstrong.com Git - neurodebian.git/blob - survey/makestats
More advice.
[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 = ['#AA2029', '#D1942B', '#7FB142', '#69A7CE']
20 os_order = ['linux', 'mac', 'win', 'otheros']
21 time_order = ['notime', 'little', 'most', 'always']
22 time_colors = ['#FF0000', '#FF5500', '#FFAC00', '#FFFD08']
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     'otherres': '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         'psychphys': '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", "dontknow"]
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         if line.strip() == "":
95             continue
96         kv = line.split(':')
97         if kv[0] in d:
98             raise RuntimeError(
99                 "Got a line %s with a duplicate key %s whenever value for it "
100                 "is known already to be %r" % (line, kv[0], d[kv[0]]))
101         d[kv[0]] = kv[1].strip().strip('"')
102     return d
103
104
105
106 class DB(dict):
107     os_dict = load_list2dict('oslist.txt')
108     datamod_dict = load_list2dict('datamodlist.txt')
109     sw_dict = load_list2dict('swlist.txt')
110     position_dict = load_list2dict('position-dd-list.txt')
111     employer_dict = load_list2dict('employer-dd-list.txt')
112     ratings_dict = load_list2dict('ratingslist.txt')
113     vm_dict = load_list2dict('vmlist.txt')
114
115     def __init__(self, srcdir):
116         # eats the whole directory
117         if srcdir is None:
118             return
119         datafilenames = glob('%s/*.json' % srcdir)
120         for dfn in datafilenames:
121             rawdata = jsonload(open(dfn))
122             self[rawdata['timestamp']] = rawdata
123
124     def get_unique(self, key):
125         # return a set of all (unique) values for a field id
126         uniq = set()
127         for d in self.values():
128             if key in d:
129                 el = d[key]
130                 if isinstance(el, list):
131                     uniq = uniq.union(el)
132                 else:
133                     uniq = uniq.union((el,))
134         return uniq
135
136     def get_not_none(self, key):
137         # return a list of all values of a specific field id
138         # the second return value is count of submission that did not have data
139         # for this field id
140         val = []
141         missing = 0
142         for d in self.values():
143             if key in d:
144                 el = d[key]
145                 if isinstance(el, list):
146                     val.extend(el)
147                 else:
148                     if el == 'none':
149                         missing += 1
150                     else:
151                         val.append(el)
152             else:
153                 missing += 1
154         return val, missing
155
156     def get_counts(self, key):
157         # return a dict with field values as keys and respective submission 
158         # count as value
159         vals = self.get_not_none(key)[0]
160         uniq = np.unique(vals)
161         counts = dict(zip(uniq, [vals.count(u) for u in uniq]))
162         return counts
163
164     def select_match(self, key, values):
165         # return a db with all submissions were a field id has one of the
166         # supplied values
167         match = DB(None)
168         for k, v in self.items():
169             if not key in v:
170                 continue
171             el = v[key]
172             if isinstance(el, list):
173                 if len(set(values).intersection(el)):
174                     match[k] = v
175             elif el in values:
176                 match[k] = v
177         return match
178
179     def get_nice_name(self, id):
180         srcs = [DB.os_dict, os_cat_names, DB.sw_dict, sw_categories,
181                 resource_categories, time_categories,
182                 DB.datamod_dict, DB.position_dict, DB.employer_dict,
183                 DB.vm_dict, DB.ratings_dict]
184         for src in srcs:
185             if id in src:
186                 return src[id]
187         # not found, nothing nicer
188         return id
189
190
191 def mkpic_os_per_env(db, destdir):
192     envs = ['pers_os', 'man_os', 'virt_host_os', 'virt_guest_os']
193     env_names = ['Personal', 'Managed', 'Virt. Host', 'Virt. Guest']
194     env_stats = {}
195     for env in envs:
196         counts = db.get_counts(env)
197         stats = dict(zip(os_family.keys(), [0] * len(os_family)))
198         for os in counts:
199             stats[os_family_rev[os]] += counts[os]
200         total_count = np.sum(stats.values())
201         for osf in stats:
202             if not total_count:
203                 stats[osf] = 0
204             else:
205                 stats[osf] = float(stats[osf]) / total_count
206         env_stats[env] = stats
207     # make stacked barplot
208     pl.figure(figsize=(7.5, 4))
209     x = np.arange(len(envs))
210     bottoms = np.zeros(len(envs))
211     for i, os in enumerate(os_order):
212         stat = [env_stats[e][os] for e in envs[::-1]]
213         pl.barh(x, stat, left=bottoms, color=os_colors[i],
214                label=db.get_nice_name(os), height=0.8)
215         bottoms += stat
216     pl.legend(loc='center left')
217     pl.yticks(x + 0.4,  env_names[::-1])
218     pl.ylim(-0.25, len(envs))
219     pl.xlim(0,1)
220     pl.title("Operating system preference by environment")
221     pl.xlabel("Fraction of submissions")
222     pl.subplots_adjust(left=0.15, right=0.97)
223     pl.savefig('%s/ospref_by_env.png' % destdir, format='png', dpi=80)
224
225
226 def mkpic_time_per_env(db, destdir):
227     envs = ['pers_time', 'man_time', 'virt_time']
228     env_names = ['Personal', 'Managed', 'Virtual']
229     env_stats = {}
230     for env in envs:
231         counts = dict(zip(time_order, [0] * len(time_order)))
232         counts.update(db.get_counts(env))
233         total_count = np.sum(counts.values())
234         for c in counts:
235             counts[c] = float(counts[c]) / total_count
236         env_stats[env] = counts
237     # make stacked barplot
238     pl.figure(figsize=(7.5, 4))
239     x = np.arange(len(envs))
240     bottoms = np.zeros(len(envs))
241     for i, t in enumerate(time_order):
242         stat = [env_stats[e][t] for e in envs]
243         pl.barh(x, stat, left=bottoms, color=time_colors[i],
244                label=db.get_nice_name(t), height=.6)
245         bottoms += stat
246     pl.legend(loc='upper left')
247     pl.yticks(x + 0.2,  env_names)
248     pl.ylim(-0.4, len(envs))
249     pl.title("Research activity time by environment")
250     pl.xlabel("Fraction of submissions")
251     pl.subplots_adjust(right=0.97)
252     pl.savefig('%s/time_by_env.png' % destdir, format='png', dpi=80)
253
254
255 def mkpic_submissions_per_key(db, destdir, key, title, sortby='name',
256                             multiple=False):
257     counts = db.get_counts(key)
258     pl.figure(figsize=(6.4, (len(counts)-2) * 0.4 + 2))
259     if not len(counts): tmargin = 0.4
260     else: tmargin = .8/len(counts)
261     if tmargin > 0.3: tmargin = 0.3
262     pl.subplots_adjust(left=0.03, right=0.97, top=1-tmargin, bottom=tmargin)
263     pl.title(title)
264     if not len(counts):
265         pl.text(.5, .5, "[Insufficient data for this figure]",
266                 horizontalalignment='center')
267         pl.axis('off')
268     else:
269         # sort by name
270         if sortby == 'name':
271             stats = sorted(counts.items(), cmp=lambda x, y: cmp(x[0], y[0]))
272         elif sortby == 'count':
273             stats = sorted(counts.items(), cmp=lambda x, y: cmp(x[1], y[1]))[::-1]
274         else:
275             raise ValueError("Specify either name or count for sortby")
276         x = np.arange(len(stats))
277         pl.barh(x + (1./8), [s[1] for s in stats[::-1]], height=0.75, color = '#008200')
278         pl.yticks(x + 0.5,  ['' for s in stats])
279         text_offset = pl.gca().get_xlim()[1] / 30.
280         for i, s in enumerate(stats[::-1]):
281             pl.text(text_offset, i+.5, db.get_nice_name(s[0]) + " [%d]" % (s[1],),
282                     horizontalalignment='left',
283                     verticalalignment='center',
284                     bbox=dict(facecolor='white', alpha=0.8, edgecolor='white'))
285         pl.ylim(0, len(stats))
286         yl = "Number of submissions"
287         if multiple:
288             yl += "\n(multiple choices per submission possible)"
289         pl.xlabel(yl)
290     pl.savefig('%s/submissions_per_%s.png' % (destdir, key), format='png', dpi=80)
291
292
293 def mkpic_software(db, destdir):
294     for typ in sw_categories.keys():
295         mkpic_submissions_per_key(
296             db, destdir, 'sw_%s' % typ,
297             title="Software popularity: %s" % db.get_nice_name(typ),
298             sortby='count')
299
300 def mkpic_rating_by_os(db, env, items, destdir, title):
301     pl.figure(figsize=(6.4, 4.8))
302     for i, os in enumerate(os_order):
303         ratings = [db.select_match(env,
304                         os_family[os]).get_not_none('%s' % (it,))[0]
305                             for it in items]
306         plot_bars(ratings, offset=((i+1)*0.2)-0.1, color=os_colors[i],
307                   title=title, ylabel="Mean rating", label=db.get_nice_name(os))
308     pl.ylim((0,3))
309     pl.xlim((0,len(items)))
310     pl.yticks((0, 3), ['Disagree', 'Agree'], rotation=90)
311     pl.xticks(np.arange(len(items))+0.5, [i[-2:] for i in items],
312               horizontalalignment='center')
313     pl.legend(loc='lower right')
314     pl.savefig('%s/ratings_%s.png' % (destdir, env), format='png', dpi=80)
315
316 def mkpic_rating_by_os_hor_joined(db, env, items, destdir, title,
317                                   intro_sentence="I agree with the statements"):
318     per_os_width = 10
319     max_rating = 4
320     #pl.figure(figsize=(6.4, 4.8))
321     nos = len(os_order)
322     rst = open('figures/ratings_%s.rst' % env, 'w')
323     rst.write("""
324
325 %s
326 %s
327
328 %s
329
330 .. raw:: html
331
332    <table>
333     """ % (title, '=' * len(title), intro_sentence))
334     for k, it in enumerate(items):
335         if k == 0:
336             pl.figure(figsize=(3.2, 0.75))
337         else:
338             pl.figure(figsize=(3.2, 0.5))
339         it_nice = db.get_nice_name(it)#.lstrip('.').lstrip(' ')
340         it_nice = it_nice[0].upper() + it_nice[1:]
341         for i, os in enumerate(os_order):
342             ratings = np.array(db.select_match(env,
343                                                os_family[os]).get_not_none('%s' % (it,))[0])
344             # assume that we have 4 grades from 0 to 3
345             if len(ratings):
346                 assert(max(ratings) < max_rating)
347             # Complement with errorbar
348             if len(ratings):
349                 meanstat = np.mean(ratings)
350                 meanstat_point = per_os_width * (float(meanstat))/(max_rating-1)
351                 # standard error of estimate
352                 errstat = len(ratings) > 1 and np.std(ratings)/np.sqrt(len(ratings)-1) or 0
353
354                 if True:
355                     # Beautiful piece not yet appreciated by the audience
356                     total = len(ratings)
357                     bottom = 0
358                     for r in range(max_rating):
359                         stat = np.sum(ratings == r) * meanstat_point / float(total)
360                         #print r, it, os, stat, total
361                         #if it == "pers_r8" and os == "linux" and r == 3:
362                         #    import pydb; pydb.debugger()
363                         kwargs = dict(label=None)
364                         if stat:
365                             pl.barh(1.0/nos * (nos - 1 - i), stat, left=bottom, color=os_colors[i],
366                                     height=.25, alpha=0.25 + r/float(max_rating),
367                                     label=None,
368                                     edgecolor=os_colors[i])
369                         bottom += stat
370                 else:
371                     pl.barh(1.0/nos * (nos - 1 - i), meanstat_point, left=0,
372                             color=os_colors[i], height=.25, alpha=1.0, label=None)
373                 pl.errorbar([meanstat_point],
374                             [1.0/nos * (nos - 0.5 - i)],
375                             xerr=[errstat], fmt='o', color=os_colors[i], ecolor='k')
376         pl.xlim((0, per_os_width))
377         if k == 0:
378             pl.text(0, 1.1, "Disagree", horizontalalignment='left')
379             pl.text(per_os_width, 1.1, "Agree", horizontalalignment='right')
380             pl.ylim((0, 1.5))
381         else:
382             pl.ylim((0, 1))
383         pl.axis('off')
384         pl.subplots_adjust(left=0.00, right=1., bottom=0.0, top=1,
385                        wspace=0.05, hspace=0.05)
386         fname = '%s/ratings_%s_%s.png' % (destdir, env, it)
387         pl.savefig(fname, format='png', dpi=80)
388         pl.close()
389         oddrow_s = k % 2 == 0 and ' class="oddrow"' or ''
390         rst.write("""
391         <tr%(oddrow_s)s>
392         <td>%(it_nice)s</td>
393         <td><img border="0" alt="%(fname)s" src="%(fname)s" /></td> </tr>"""
394                   % (locals()))
395
396     rst.write("""
397     </table>
398
399     """)
400     rst.close()
401     return
402
403
404 def main(srcdir, destdir):
405     db = DB(srcdir)
406     if not os.path.exists(destdir):
407         os.makedirs(destdir)
408
409     mkpic_submissions_per_key(
410         db, destdir, 'virt_prod', sortby='count',
411         title='Virtualization product popularity')
412
413     mkpic_submissions_per_key(
414         db, destdir, 'bg_datamod', sortby='count',
415         title='Submissions per data modality')
416
417     mkpic_submissions_per_key(
418         db, destdir, 'bg_position', title='Submissions per position', sortby='count')
419
420     mkpic_submissions_per_key(
421         db, destdir, 'bg_country', title='Submissions per country', sortby='count')
422
423     mkpic_submissions_per_key(
424         db, destdir, 'bg_employer', title='Submissions per venue', sortby='count')
425
426     mkpic_submissions_per_key(
427         db, destdir, 'software_resource', title='Software resource popularity', sortby='count')
428
429     for pic in [mkpic_os_per_env, mkpic_software, mkpic_time_per_env]:
430         pic(db, destdir)
431     mkpic_rating_by_os_hor_joined(db, 'pers_os', ['pers_r%i' % i for i in range(1, 9)], destdir,
432                        "Personal environment", "I prefer this particular scientific software environment because ...")
433     mkpic_rating_by_os_hor_joined(db, 'man_os', ['man_r%i' % i for i in range(1, 5)], destdir,
434                        "Managed environment")
435     mkpic_rating_by_os_hor_joined(db, 'virt_host_os', ['virt_r%i' % i for i in range(1, 4)], destdir,
436                        "Virtual environment (by host OS)")
437
438     # submission stats: this is RST
439     statsfile = open('%s/stats.txt' % destdir, 'w')
440     statsfile.write('::\n\n  Number of submissions: %i\n' % len(db))
441     statsfile.write('  Statistics last updated: %s\n\n' \
442             % time.strftime('%A, %B %d %Y, %H:%M:%S UTC', time.gmtime()))
443     statsfile.close()
444
445 if __name__ == '__main__':
446     main(sys.argv[1], sys.argv[2])