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