]> git.donarmstrong.com Git - neurodebian.git/blob - survey/makestats
Also for stats report which repo and which job number use our setup
[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, predef_keys=None):
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         if not predef_keys is None:
171             ret = dict(zip(predef_keys, [0] * len(predef_keys)))
172         else:
173             ret = {}
174         ret.update(counts)
175         return ret
176
177     def select_match(self, key, values):
178         # return a db with all submissions were a field id has one of the
179         # supplied values
180         match = DB(None)
181         for k, v in self.items():
182             if not key in v:
183                 continue
184             el = v[key]
185             if isinstance(el, list):
186                 if len(set(values).intersection(el)):
187                     match[k] = v
188             elif el in values:
189                 match[k] = v
190         return match
191
192     def select_match_exactly(self, key, values):
193         # return a db with all submissions were a field id has value
194         # equal to the supplied
195         match = DB(None)
196         set_values = set(values)
197         for k, v in self.items():
198             if not key in v:
199                 continue
200             el = v[key]
201             if isinstance(el, list):
202                 if set(el) == set_values:
203                     match[k] = v
204             elif set([el]) == set_values:
205                 match[k] = v
206         return match
207
208     def get_nice_name(self, id):
209         srcs = [DB.os_dict, os_cat_names, DB.sw_dict, sw_categories,
210                 resource_categories, time_categories,
211                 DB.datamod_dict, DB.position_dict, DB.employer_dict,
212                 DB.vm_dict, DB.ratings_dict]
213         suffix = u'$^†$' if id in fresh_keys else ''
214         for src in srcs:
215             if id in src:
216                 return src[id] + suffix
217         # not found, nothing nicer
218         return id + suffix
219
220
221 def mkpic_os_per_env(db, destdir):
222     envs = ['pers_os', 'man_os', 'virt_host_os', 'virt_guest_os']
223     env_names = ['Personal', 'Managed', 'Virt. Host', 'Virt. Guest']
224     env_stats = {}
225     for env in envs:
226         counts = db.get_counts(env)
227         stats = dict(zip(os_family.keys(), [0] * len(os_family)))
228         for os in counts:
229             stats[os_family_rev[os]] += counts[os]
230         total_count = np.sum(stats.values())
231         for osf in stats:
232             if not total_count:
233                 stats[osf] = 0
234             else:
235                 stats[osf] = float(stats[osf]) / total_count
236         env_stats[env] = stats
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, os in enumerate(os_order):
242         stat = [env_stats[e][os] for e in envs[::-1]]
243         pl.barh(x, stat, left=bottoms, color=os_colors[i],
244                label=db.get_nice_name(os), height=0.8)
245         bottoms += stat
246     pl.legend(loc='center left')
247     pl.yticks(x + 0.4,  env_names[::-1])
248     pl.ylim(-0.25, len(envs))
249     pl.xlim(0,1)
250     pl.title("Operating system preference by environment")
251     pl.xlabel("Fraction of submissions")
252     pl.subplots_adjust(left=0.15, right=0.97)
253     pl.savefig('%s/ospref_by_env.png' % destdir, format='png', dpi=80)
254
255
256 def mkpic_time_per_env(db, destdir):
257     envs = ['pers_time', 'man_time', 'virt_time']
258     env_names = ['Personal', 'Managed', 'Virtual']
259     env_stats = {}
260     for env in envs:
261         counts = dict(zip(time_order, [0] * len(time_order)))
262         counts.update(db.get_counts(env))
263         total_count = np.sum(counts.values())
264         for c in counts:
265             counts[c] = float(counts[c]) / total_count
266         env_stats[env] = counts
267     # make stacked barplot
268     pl.figure(figsize=(7.5, 4))
269     x = np.arange(len(envs))
270     bottoms = np.zeros(len(envs))
271     for i, t in enumerate(time_order):
272         stat = [env_stats[e][t] for e in envs[::-1]]
273         pl.barh(x, stat, left=bottoms, color=time_colors[i],
274                label=db.get_nice_name(t), height=.6)
275         bottoms += stat
276     pl.legend(loc='lower left')
277     pl.yticks(x + 0.2,  env_names[::-1])
278     pl.ylim(-0.4, len(envs))
279     pl.title("Research activity time by environment")
280     pl.xlabel("Fraction of submissions")
281     pl.subplots_adjust(right=0.97)
282     pl.savefig('%s/time_by_env.png' % destdir, format='png', dpi=80)
283
284
285 def mkpic_submissions_per_key(db, destdir, key, title, sortby='name',
286                             multiple=False):
287     counts = db.get_counts(key)
288     pl.figure(figsize=(6.4, (len(counts)-2) * 0.4 + 2))
289     if not len(counts): tmargin = 0.4
290     else: tmargin = .8/len(counts)
291     if tmargin > 0.3: tmargin = 0.3
292     pl.subplots_adjust(left=0.03, right=0.97, top=1-tmargin, bottom=tmargin)
293     pl.title(title)
294     if not len(counts):
295         pl.text(.5, .5, "[Insufficient data for this figure]",
296                 horizontalalignment='center')
297         pl.axis('off')
298     else:
299         # sort by name
300         if sortby == 'name':
301             stats = sorted(counts.items(), cmp=lambda x, y: cmp(x[0], y[0]))
302         elif sortby == 'count':
303             stats = sorted(counts.items(), cmp=lambda x, y: cmp(x[1], y[1]))[::-1]
304         else:
305             raise ValueError("Specify either name or count for sortby")
306         x = np.arange(len(stats))
307         pl.barh(x + (1./8), [s[1] for s in stats[::-1]], height=0.75, color = '#008200')
308         pl.yticks(x + 0.5,  ['' for s in stats])
309         text_offset = pl.gca().get_xlim()[1] / 30.
310         for i, s in enumerate(stats[::-1]):
311             pl.text(text_offset, i+.5, db.get_nice_name(s[0]) + " [%d]" % (s[1],),
312                     horizontalalignment='left',
313                     verticalalignment='center',
314                     bbox=dict(facecolor='white', alpha=0.8, edgecolor='white'))
315         pl.ylim(0, len(stats))
316         yl = "Number of submissions"
317         if multiple:
318             yl += "\n(multiple choices per submission possible)"
319         pl.xlabel(yl)
320     pl.savefig('%s/submissions_per_%s.png' % (destdir, key), format='png', dpi=80)
321
322
323 def mkpic_software(db, destdir):
324     for typ in sw_categories.keys():
325         mkpic_submissions_per_key(
326             db, destdir, 'sw_%s' % typ,
327             title="Software popularity: %s" % db.get_nice_name(typ),
328             sortby='count')
329
330 def mkpic_rating_by_os(db, env, items, destdir, title):
331     from mvpa.misc.plot.base import plot_bars
332
333     pl.figure(figsize=(6.4, 4.8))
334     for i, os in enumerate(os_order):
335         ratings = [db.select_match(env,
336                         os_family[os]).get_not_none('%s' % (it,))[0]
337                             for it in items]
338         plot_bars(ratings, offset=((i+1)*0.2)-0.1, color=os_colors[i],
339                   title=title, ylabel="Mean rating", label=db.get_nice_name(os))
340     pl.ylim((0,3))
341     pl.xlim((0,len(items)))
342     pl.yticks((0, 3), ['Disagree', 'Agree'], rotation=90)
343     pl.xticks(np.arange(len(items))+0.5, [i[-2:] for i in items],
344               horizontalalignment='center')
345     pl.legend(loc='lower right')
346     pl.savefig('%s/ratings_%s.png' % (destdir, env), format='png', dpi=80)
347
348 def mkpic_rating_by_os_hor_joined(db, env, items, destdir='.', title=None,
349                                   intro_sentence="I agree with the statements",
350                                   suffix='', max_rating=4):
351     per_os_width = 1
352     #pl.figure(figsize=(6.4, 4.8))
353     if max_rating is None:
354         assert(len(items) == 1)
355         # We need to query for it
356         field = items[0]
357         max_rating = np.max([db[k][field] for k in db if field in db[k]]) + 1
358         print "max ", max_rating
359     nos = len(os_order)
360     rst = open('figures/ratings_%s%s.rst' % (env, suffix), 'w')
361     rst.write("""
362
363 %s
364 %s
365
366 %s
367
368 .. raw:: html
369
370    <table>
371     """ % (title, '=' * len(title), intro_sentence))
372     for k, it in enumerate(items):
373         if k == 0:
374             pl.figure(figsize=(3.2, 0.75))
375         else:
376             pl.figure(figsize=(3.2, 0.5))
377         it_nice = db.get_nice_name(it)#.lstrip('.').lstrip(' ')
378         it_nice = it_nice[0].upper() + it_nice[1:]
379         for i, os in enumerate(os_order):
380             ratings = np.array(db.select_match(env,
381                                                os_family[os]).get_not_none('%s' % (it,))[0])
382             #if len(ratings):
383             #    assert(max(ratings) < max_rating)
384             # Complement with errorbar
385             if len(ratings):
386                 scaling = float(per_os_width)/(max_rating-1)
387                 meanstat = np.mean(ratings)
388                 meanstat_point = scaling * meanstat
389                 # standard error of estimate
390                 errstat_point = len(ratings) > 1 and scaling*np.std(ratings)/np.sqrt(len(ratings)-1) or 0
391                 #print ratings, meanstat, meanstat_point, errstat_point
392                 if True:
393                     # Beautiful piece not yet appreciated by the audience
394                     total = len(ratings)
395                     bottom = 0
396                     max_rating_max = max(max_rating, max(ratings)+1)
397                     for r in sorted(set(ratings)):#range(max_rating_max):
398                         stat = np.sum(ratings == r) * meanstat_point / float(total)
399                         #print r, it, os, stat, total
400                         #if it == "pers_r8" and os == "linux" and r == 3:
401                         #    import pydb; pydb.debugger()
402                         kwargs = dict(label=None)
403                         if stat:
404                             pl.barh(1.0/nos * (nos - 1 - i), stat, left=bottom, color=os_colors[i],
405                                     height=.25, alpha=1./max_rating_max + r/float(max_rating_max),
406                                     label=None,
407                                     edgecolor=os_colors[i])
408                         bottom += stat
409                 else:
410                     pl.barh(1.0/nos * (nos - 1 - i), meanstat_point, left=0,
411                             color=os_colors[i], height=.25, alpha=1.0, label=None)
412                 pl.errorbar([meanstat_point],
413                             [1.0/nos * (nos - 0.5 - i)],
414                             xerr=[errstat_point], fmt='o', color=os_colors[i], ecolor='k')
415         pl.xlim((0, per_os_width))
416         if k == 0 and max_rating == 4:  # ad-hoc: only for those disagree/agree
417             pl.text(0, 1.1, "Disagree", horizontalalignment='left')
418             pl.text(per_os_width, 1.1, "Agree", horizontalalignment='right')
419             pl.ylim((0, 1.5))
420         else:
421             pl.ylim((0, 1))
422         pl.axis('off')
423         pl.subplots_adjust(left=0.00, right=1., bottom=0.0, top=1,
424                        wspace=0.05, hspace=0.05)
425         fname = '%s/ratings_%s_%s%s.png' % (destdir, env, it, suffix)
426         pl.savefig(fname, format='png', dpi=80)
427         pl.close()
428         oddrow_s = k % 2 == 0 and ' class="oddrow"' or ''
429         rst.write("""
430         <tr%(oddrow_s)s>
431         <td>%(it_nice)s</td>
432         <td><img border="0" alt="%(fname)s" src="%(fname)s" /></td> </tr>"""
433                   % (locals()))
434
435     rst.write("""
436     </table>
437
438     """)
439     rst.close()
440     return
441
442
443 def main(srcdir, destdir):
444     db = DB(srcdir)
445     if False:
446         ## Plot maintenance time per each group
447         # assess what would be our range
448         pmts, _ = db.get_not_none('pers_maint_time')
449         max_rating = int(np.mean(pmts) + np.std(pmts))
450         for pos in db.get_unique('bg_position'):
451             print pos
452             mkpic_rating_by_os_hor_joined(db.select_match('bg_position', pos),
453                                           'pers_os', ['pers_maint_time'], destdir,
454                                           "Personal environment", "", suffix='_maint_time_%s' % pos,
455                                           max_rating=max_rating)
456
457     ## db2 = db
458     # custom selection for people dealing more with hardware
459     # any electrophys
460     ## db = db2.select_match('bg_datamod', (('ephys'),))
461     # or only selected ones (so no fmri/pet etc)
462     ## db = db2.select_match_exactly('bg_datamod', (('ephys'), ('behav'),))
463     ## db.update(db2.select_match_exactly('bg_datamod', (('ephys'),)))
464     ## db.update(db2.select_match_exactly('bg_datamod', (('ephys'), ('genetic'),)))
465     ## db.update(db2.select_match_exactly('bg_datamod', (('ephys'), ('simulation'),)))
466     ## db.update(db2.select_match_exactly('bg_datamod', (('ephys'), ('meeg'),)))
467
468     if not os.path.exists(destdir):
469         os.makedirs(destdir)
470
471     mkpic_submissions_per_key(
472         db, destdir, 'virt_prod', sortby='count',
473         title='Virtualization product popularity')
474
475     mkpic_submissions_per_key(
476         db, destdir, 'bg_datamod', sortby='count',
477         title='Submissions per data modality')
478
479     mkpic_submissions_per_key(
480         db, destdir, 'bg_position', title='Submissions per position', sortby='count')
481
482     mkpic_submissions_per_key(
483         db, destdir, 'bg_country', title='Submissions per country', sortby='count')
484
485     mkpic_submissions_per_key(
486         db, destdir, 'bg_employer', title='Submissions per venue', sortby='count')
487
488     mkpic_submissions_per_key(
489         db, destdir, 'software_resource', title='Software resource popularity', sortby='count')
490
491     for pic in [mkpic_os_per_env, mkpic_software, mkpic_time_per_env]:
492         pic(db, destdir)
493
494
495     mkpic_rating_by_os_hor_joined(db, 'pers_os', ['pers_r%i' % i for i in range(1, 9)], destdir,
496                        "Personal environment", "I prefer this particular scientific software environment because ...")
497     mkpic_rating_by_os_hor_joined(db, 'man_os', ['man_r%i' % i for i in range(1, 6)], destdir,
498                        "Managed environment")
499     mkpic_rating_by_os_hor_joined(db, 'virt_host_os', ['virt_r%i' % i for i in range(1, 5)], destdir,
500                        "Virtual environment (by host OS)")
501     mkpic_rating_by_os_hor_joined(db, 'virt_guest_os', ['virt_r%i' % i for i in range(1, 5)], destdir,
502                        "Virtual environment (by guest OS)")
503
504     ## mkpic_rating_by_os_hor_joined(db.select_match('virt_prod', (('vmware'),)),
505     ##                               'virt_host_os', ['virt_r%i' % i for i in range(1, 5)], destdir,
506     ##                               "Virtualbox virtual environment (by host OS)")
507
508     # submission stats: this is RST
509     statsfile = open('%s/stats.txt' % destdir, 'w')
510     statsfile.write('::\n\n  Number of submissions: %i\n' % len(db))
511     statsfile.write('  Statistics last updated: %s\n\n' \
512             % time.strftime('%A, %B %d %Y, %H:%M:%S UTC', time.gmtime()))
513     statsfile.close()
514
515 if __name__ == '__main__':
516     main(sys.argv[1], sys.argv[2])
517     #main('dataout', 'figures')