]> git.donarmstrong.com Git - neurodebian.git/blob - survey/makestats
Merge branch 'master' of alioth:/git/pkg-exppsy/neurodebian
[neurodebian.git] / survey / makestats
1 #!/usr/bin/python
2
3 from glob import glob
4 try:
5     from json import load as jload
6     def jsonload(f):
7         return jload(f)
8 except ImportError:
9     from json import read as jread
10     def jsonload(f):
11         return jread(f.read())
12 import sys, os
13 import pylab as pl
14 import numpy as np
15 import time
16
17 # uniform colors for OS results
18 os_colors = ['#AA2029', '#D1942B', '#7FB142', '#69A7CE']
19 os_order = ['linux', 'mac', 'win', 'otheros']
20 time_order = ['notime', 'little', 'most', 'always']
21 time_colors = ['#FF0000', '#FF5500', '#FFAC00', '#FFFD08']
22 time_categories = {
23         'notime': "don't use it",
24         'little': "less than 50%",
25         'most': "more than 50%",
26         'always': "always"
27         }
28 # resources
29 resource_categories = {
30     'vendor': 'Vendor/Project website',
31     'retailer': 'Retailer',
32     'os': 'Operating system',
33     'cpan': 'CPAN',
34     'cran': 'CRAN',
35     'epel': 'EPEL',
36     'fink': 'Fink',
37     'freebsdports': 'FreeBSD ports',
38     'incf': 'INCF',
39     'macports': 'Macports',
40     'matlabcentral': 'Matlab Central',
41     'neurodebian': 'NeuroDebian',
42     'nitrc': 'NITRC',
43     'pypi': 'PyPi',
44     'pythonbundles': 'Python bundles',
45     'sourceforge': 'Sourceforge',
46     'otherres': 'Other resource'
47     }
48 # software categories
49 sw_categories = {
50         'general': 'General computing',
51         'dc': 'Distributed computing',
52         'img': 'Brain imaging',
53         'datamanage': 'Data management',
54         'neusys': 'Neural systems modeling',
55         'electro': 'Electrophysiology, MEG/EEG',
56         'bci': 'Brain-computer interface',
57         'acq': 'Hardware interface/Data acquisition',
58         'rt': 'Real-time solutions',
59         'psychphys': 'Psychophysics/Experiment control'
60         }
61
62 # some meaningful groups of OSes
63 redhat_family = ["rhel", "centos", "fedora", "scilinux"]
64 debian_family = ["debian", "ubuntu", "biolinux"]
65 suse_family = ["suse", "slel"]
66 other_linux_family = ["gentoo", "mandriva", "arch", "slackware", "otherlinux"]
67 other_family = ["starbsd", "unix", "qnx", "beos", "solaris", "other", "dontknow"]
68
69 os_cat_names = {
70         'win': 'Windows',
71         'mac': 'Mac OS',
72         'linux': 'GNU/Linux',
73         'otheros': 'Other OS'
74         }
75
76 os_family = {
77         'win': ["windows"],
78         'mac': ["macosx"],
79         'linux': redhat_family + debian_family + suse_family + other_linux_family,
80         'otheros': other_family
81         }
82 # end the reverse mapping
83 os_family_rev = {}
84 for ost in os_family:
85     for os_ in os_family[ost]:
86         os_family_rev[os_] = ost
87
88
89 def load_list2dict(name):
90     d = {}
91     lfile = open(name)
92     for line in lfile:
93         if line.strip() == "":
94             continue
95         kv = line.split(':')
96         if kv[0] in d:
97             raise RuntimeError(
98                 "Got a line %s with a duplicate key %s whenever value for it "
99                 "is known already to be %r" % (line, kv[0], d[kv[0]]))
100         d[kv[0]] = kv[1].strip().strip('"')
101     return d
102
103
104
105 class DB(dict):
106     os_dict = load_list2dict('oslist.txt')
107     datamod_dict = load_list2dict('datamodlist.txt')
108     sw_dict = load_list2dict('swlist.txt')
109     position_dict = load_list2dict('position-dd-list.txt')
110     employer_dict = load_list2dict('employer-dd-list.txt')
111     ratings_dict = load_list2dict('ratingslist.txt')
112     vm_dict = load_list2dict('vmlist.txt')
113
114     def __init__(self, srcdir):
115         # eats the whole directory
116         if srcdir is None:
117             return
118         datafilenames = glob('%s/*.json' % srcdir)
119         for dfn in datafilenames:
120             rawdata = jsonload(open(dfn))
121             self[rawdata['timestamp']] = rawdata
122
123     def get_unique(self, key):
124         # return a set of all (unique) values for a field id
125         uniq = set()
126         for d in self.values():
127             if key in d:
128                 el = d[key]
129                 if isinstance(el, list):
130                     uniq = uniq.union(el)
131                 else:
132                     uniq = uniq.union((el,))
133         return uniq
134
135     def get_not_none(self, key):
136         # return a list of all values of a specific field id
137         # the second return value is count of submission that did not have data
138         # for this field id
139         val = []
140         missing = 0
141         for d in self.values():
142             if key in d:
143                 el = d[key]
144                 if isinstance(el, list):
145                     val.extend(el)
146                 else:
147                     if el == 'none':
148                         missing += 1
149                     else:
150                         val.append(el)
151             else:
152                 missing += 1
153         return val, missing
154
155     def get_counts(self, key, predef_keys=None):
156         # return a dict with field values as keys and respective submission 
157         # count as value
158         vals = self.get_not_none(key)[0]
159         uniq = np.unique(vals)
160         counts = dict(zip(uniq, [vals.count(u) for u in uniq]))
161         if not predef_keys is None:
162             ret = dict(zip(predef_keys, [0] * len(predef_keys)))
163         else:
164             ret = {}
165         ret.update(counts)
166         return ret
167
168     def select_match(self, key, values):
169         # return a db with all submissions were a field id has one of the
170         # supplied values
171         match = DB(None)
172         for k, v in self.items():
173             if not key in v:
174                 continue
175             el = v[key]
176             if isinstance(el, list):
177                 if len(set(values).intersection(el)):
178                     match[k] = v
179             elif el in values:
180                 match[k] = v
181         return match
182
183     def select_match_exactly(self, key, values):
184         # return a db with all submissions were a field id has value
185         # equal to the supplied
186         match = DB(None)
187         set_values = set(values)
188         for k, v in self.items():
189             if not key in v:
190                 continue
191             el = v[key]
192             if isinstance(el, list):
193                 if set(el) == set_values:
194                     match[k] = v
195             elif set([el]) == set_values:
196                 match[k] = v
197         return match
198
199     def get_nice_name(self, id):
200         srcs = [DB.os_dict, os_cat_names, DB.sw_dict, sw_categories,
201                 resource_categories, time_categories,
202                 DB.datamod_dict, DB.position_dict, DB.employer_dict,
203                 DB.vm_dict, DB.ratings_dict]
204         for src in srcs:
205             if id in src:
206                 return src[id]
207         # not found, nothing nicer
208         return id
209
210
211 def mkpic_os_per_env(db, destdir):
212     envs = ['pers_os', 'man_os', 'virt_host_os', 'virt_guest_os']
213     env_names = ['Personal', 'Managed', 'Virt. Host', 'Virt. Guest']
214     env_stats = {}
215     for env in envs:
216         counts = db.get_counts(env)
217         stats = dict(zip(os_family.keys(), [0] * len(os_family)))
218         for os in counts:
219             stats[os_family_rev[os]] += counts[os]
220         total_count = np.sum(stats.values())
221         for osf in stats:
222             if not total_count:
223                 stats[osf] = 0
224             else:
225                 stats[osf] = float(stats[osf]) / total_count
226         env_stats[env] = stats
227     # make stacked barplot
228     pl.figure(figsize=(7.5, 4))
229     x = np.arange(len(envs))
230     bottoms = np.zeros(len(envs))
231     for i, os in enumerate(os_order):
232         stat = [env_stats[e][os] for e in envs[::-1]]
233         pl.barh(x, stat, left=bottoms, color=os_colors[i],
234                label=db.get_nice_name(os), height=0.8)
235         bottoms += stat
236     pl.legend(loc='center left')
237     pl.yticks(x + 0.4,  env_names[::-1])
238     pl.ylim(-0.25, len(envs))
239     pl.xlim(0,1)
240     pl.title("Operating system preference by environment")
241     pl.xlabel("Fraction of submissions")
242     pl.subplots_adjust(left=0.15, right=0.97)
243     pl.savefig('%s/ospref_by_env.png' % destdir, format='png', dpi=80)
244
245
246 def mkpic_time_per_env(db, destdir):
247     envs = ['pers_time', 'man_time', 'virt_time']
248     env_names = ['Personal', 'Managed', 'Virtual']
249     env_stats = {}
250     for env in envs:
251         counts = dict(zip(time_order, [0] * len(time_order)))
252         counts.update(db.get_counts(env))
253         total_count = np.sum(counts.values())
254         for c in counts:
255             counts[c] = float(counts[c]) / total_count
256         env_stats[env] = counts
257     # make stacked barplot
258     pl.figure(figsize=(7.5, 4))
259     x = np.arange(len(envs))
260     bottoms = np.zeros(len(envs))
261     for i, t in enumerate(time_order):
262         stat = [env_stats[e][t] for e in envs[::-1]]
263         pl.barh(x, stat, left=bottoms, color=time_colors[i],
264                label=db.get_nice_name(t), height=.6)
265         bottoms += stat
266     pl.legend(loc='lower left')
267     pl.yticks(x + 0.2,  env_names[::-1])
268     pl.ylim(-0.4, len(envs))
269     pl.title("Research activity time by environment")
270     pl.xlabel("Fraction of submissions")
271     pl.subplots_adjust(right=0.97)
272     pl.savefig('%s/time_by_env.png' % destdir, format='png', dpi=80)
273
274
275 def mkpic_submissions_per_key(db, destdir, key, title, sortby='name',
276                             multiple=False):
277     counts = db.get_counts(key)
278     pl.figure(figsize=(6.4, (len(counts)-2) * 0.4 + 2))
279     if not len(counts): tmargin = 0.4
280     else: tmargin = .8/len(counts)
281     if tmargin > 0.3: tmargin = 0.3
282     pl.subplots_adjust(left=0.03, right=0.97, top=1-tmargin, bottom=tmargin)
283     pl.title(title)
284     if not len(counts):
285         pl.text(.5, .5, "[Insufficient data for this figure]",
286                 horizontalalignment='center')
287         pl.axis('off')
288     else:
289         # sort by name
290         if sortby == 'name':
291             stats = sorted(counts.items(), cmp=lambda x, y: cmp(x[0], y[0]))
292         elif sortby == 'count':
293             stats = sorted(counts.items(), cmp=lambda x, y: cmp(x[1], y[1]))[::-1]
294         else:
295             raise ValueError("Specify either name or count for sortby")
296         x = np.arange(len(stats))
297         pl.barh(x + (1./8), [s[1] for s in stats[::-1]], height=0.75, color = '#008200')
298         pl.yticks(x + 0.5,  ['' for s in stats])
299         text_offset = pl.gca().get_xlim()[1] / 30.
300         for i, s in enumerate(stats[::-1]):
301             pl.text(text_offset, i+.5, db.get_nice_name(s[0]) + " [%d]" % (s[1],),
302                     horizontalalignment='left',
303                     verticalalignment='center',
304                     bbox=dict(facecolor='white', alpha=0.8, edgecolor='white'))
305         pl.ylim(0, len(stats))
306         yl = "Number of submissions"
307         if multiple:
308             yl += "\n(multiple choices per submission possible)"
309         pl.xlabel(yl)
310     pl.savefig('%s/submissions_per_%s.png' % (destdir, key), format='png', dpi=80)
311
312
313 def mkpic_software(db, destdir):
314     for typ in sw_categories.keys():
315         mkpic_submissions_per_key(
316             db, destdir, 'sw_%s' % typ,
317             title="Software popularity: %s" % db.get_nice_name(typ),
318             sortby='count')
319
320 def mkpic_rating_by_os(db, env, items, destdir, title):
321     from mvpa.misc.plot.base import plot_bars
322
323     pl.figure(figsize=(6.4, 4.8))
324     for i, os in enumerate(os_order):
325         ratings = [db.select_match(env,
326                         os_family[os]).get_not_none('%s' % (it,))[0]
327                             for it in items]
328         plot_bars(ratings, offset=((i+1)*0.2)-0.1, color=os_colors[i],
329                   title=title, ylabel="Mean rating", label=db.get_nice_name(os))
330     pl.ylim((0,3))
331     pl.xlim((0,len(items)))
332     pl.yticks((0, 3), ['Disagree', 'Agree'], rotation=90)
333     pl.xticks(np.arange(len(items))+0.5, [i[-2:] for i in items],
334               horizontalalignment='center')
335     pl.legend(loc='lower right')
336     pl.savefig('%s/ratings_%s.png' % (destdir, env), format='png', dpi=80)
337
338 def mkpic_rating_by_os_hor_joined(db, env, items, destdir='.', title=None,
339                                   intro_sentence="I agree with the statements",
340                                   suffix='', max_rating=4):
341     per_os_width = 1
342     #pl.figure(figsize=(6.4, 4.8))
343     if max_rating is None:
344         assert(len(items) == 1)
345         # We need to query for it
346         field = items[0]
347         max_rating = np.max([db[k][field] for k in db if field in db[k]]) + 1
348         print "max ", max_rating
349     nos = len(os_order)
350     rst = open('figures/ratings_%s%s.rst' % (env, suffix), 'w')
351     rst.write("""
352
353 %s
354 %s
355
356 %s
357
358 .. raw:: html
359
360    <table>
361     """ % (title, '=' * len(title), intro_sentence))
362     for k, it in enumerate(items):
363         if k == 0:
364             pl.figure(figsize=(3.2, 0.75))
365         else:
366             pl.figure(figsize=(3.2, 0.5))
367         it_nice = db.get_nice_name(it)#.lstrip('.').lstrip(' ')
368         it_nice = it_nice[0].upper() + it_nice[1:]
369         for i, os in enumerate(os_order):
370             ratings = np.array(db.select_match(env,
371                                                os_family[os]).get_not_none('%s' % (it,))[0])
372             #if len(ratings):
373             #    assert(max(ratings) < max_rating)
374             # Complement with errorbar
375             if len(ratings):
376                 scaling = float(per_os_width)/(max_rating-1)
377                 meanstat = np.mean(ratings)
378                 meanstat_point = scaling * meanstat
379                 # standard error of estimate
380                 errstat_point = len(ratings) > 1 and scaling*np.std(ratings)/np.sqrt(len(ratings)-1) or 0
381                 #print ratings, meanstat, meanstat_point, errstat_point
382                 if True:
383                     # Beautiful piece not yet appreciated by the audience
384                     total = len(ratings)
385                     bottom = 0
386                     max_rating_max = max(max_rating, max(ratings)+1)
387                     for r in sorted(set(ratings)):#range(max_rating_max):
388                         stat = np.sum(ratings == r) * meanstat_point / float(total)
389                         #print r, it, os, stat, total
390                         #if it == "pers_r8" and os == "linux" and r == 3:
391                         #    import pydb; pydb.debugger()
392                         kwargs = dict(label=None)
393                         if stat:
394                             pl.barh(1.0/nos * (nos - 1 - i), stat, left=bottom, color=os_colors[i],
395                                     height=.25, alpha=1./max_rating_max + r/float(max_rating_max),
396                                     label=None,
397                                     edgecolor=os_colors[i])
398                         bottom += stat
399                 else:
400                     pl.barh(1.0/nos * (nos - 1 - i), meanstat_point, left=0,
401                             color=os_colors[i], height=.25, alpha=1.0, label=None)
402                 pl.errorbar([meanstat_point],
403                             [1.0/nos * (nos - 0.5 - i)],
404                             xerr=[errstat_point], fmt='o', color=os_colors[i], ecolor='k')
405         pl.xlim((0, per_os_width))
406         if k == 0 and max_rating == 4:  # ad-hoc: only for those disagree/agree
407             pl.text(0, 1.1, "Disagree", horizontalalignment='left')
408             pl.text(per_os_width, 1.1, "Agree", horizontalalignment='right')
409             pl.ylim((0, 1.5))
410         else:
411             pl.ylim((0, 1))
412         pl.axis('off')
413         pl.subplots_adjust(left=0.00, right=1., bottom=0.0, top=1,
414                        wspace=0.05, hspace=0.05)
415         fname = '%s/ratings_%s_%s%s.png' % (destdir, env, it, suffix)
416         pl.savefig(fname, format='png', dpi=80)
417         pl.close()
418         oddrow_s = k % 2 == 0 and ' class="oddrow"' or ''
419         rst.write("""
420         <tr%(oddrow_s)s>
421         <td>%(it_nice)s</td>
422         <td><img border="0" alt="%(fname)s" src="%(fname)s" /></td> </tr>"""
423                   % (locals()))
424
425     rst.write("""
426     </table>
427
428     """)
429     rst.close()
430     return
431
432
433 def main(srcdir, destdir):
434     db = DB(srcdir)
435     if False:
436         ## Plot maintenance time per each group
437         # assess what would be our range
438         pmts, _ = db.get_not_none('pers_maint_time')
439         max_rating = int(np.mean(pmts) + np.std(pmts))
440         for pos in db.get_unique('bg_position'):
441             print pos
442             mkpic_rating_by_os_hor_joined(db.select_match('bg_position', pos),
443                                           'pers_os', ['pers_maint_time'], destdir,
444                                           "Personal environment", "", suffix='_maint_time_%s' % pos,
445                                           max_rating=max_rating)
446
447     ## db2 = db
448     # custom selection for people dealing more with hardware
449     # any electrophys
450     ## db = db2.select_match('bg_datamod', (('ephys'),))
451     # or only selected ones (so no fmri/pet etc)
452     ## db = db2.select_match_exactly('bg_datamod', (('ephys'), ('behav'),))
453     ## db.update(db2.select_match_exactly('bg_datamod', (('ephys'),)))
454     ## db.update(db2.select_match_exactly('bg_datamod', (('ephys'), ('genetic'),)))
455     ## db.update(db2.select_match_exactly('bg_datamod', (('ephys'), ('simulation'),)))
456     ## db.update(db2.select_match_exactly('bg_datamod', (('ephys'), ('meeg'),)))
457
458     if not os.path.exists(destdir):
459         os.makedirs(destdir)
460
461     mkpic_submissions_per_key(
462         db, destdir, 'virt_prod', sortby='count',
463         title='Virtualization product popularity')
464
465     mkpic_submissions_per_key(
466         db, destdir, 'bg_datamod', sortby='count',
467         title='Submissions per data modality')
468
469     mkpic_submissions_per_key(
470         db, destdir, 'bg_position', title='Submissions per position', sortby='count')
471
472     mkpic_submissions_per_key(
473         db, destdir, 'bg_country', title='Submissions per country', sortby='count')
474
475     mkpic_submissions_per_key(
476         db, destdir, 'bg_employer', title='Submissions per venue', sortby='count')
477
478     mkpic_submissions_per_key(
479         db, destdir, 'software_resource', title='Software resource popularity', sortby='count')
480
481     for pic in [mkpic_os_per_env, mkpic_software, mkpic_time_per_env]:
482         pic(db, destdir)
483
484
485     mkpic_rating_by_os_hor_joined(db, 'pers_os', ['pers_r%i' % i for i in range(1, 9)], destdir,
486                        "Personal environment", "I prefer this particular scientific software environment because ...")
487     mkpic_rating_by_os_hor_joined(db, 'man_os', ['man_r%i' % i for i in range(1, 6)], destdir,
488                        "Managed environment")
489     mkpic_rating_by_os_hor_joined(db, 'virt_host_os', ['virt_r%i' % i for i in range(1, 5)], destdir,
490                        "Virtual environment (by host OS)")
491     mkpic_rating_by_os_hor_joined(db, 'virt_guest_os', ['virt_r%i' % i for i in range(1, 5)], destdir,
492                        "Virtual environment (by guest OS)")
493
494     ## mkpic_rating_by_os_hor_joined(db.select_match('virt_prod', (('vmware'),)),
495     ##                               'virt_host_os', ['virt_r%i' % i for i in range(1, 5)], destdir,
496     ##                               "Virtualbox virtual environment (by host OS)")
497
498     # submission stats: this is RST
499     statsfile = open('%s/stats.txt' % destdir, 'w')
500     statsfile.write('::\n\n  Number of submissions: %i\n' % len(db))
501     statsfile.write('  Statistics last updated: %s\n\n' \
502             % time.strftime('%A, %B %d %Y, %H:%M:%S UTC', time.gmtime()))
503     statsfile.close()
504
505 if __name__ == '__main__':
506     main(sys.argv[1], sys.argv[2])
507     #main('dataout', 'figures')