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