]> 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 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 = ['#B63537', '#4E4DA0', '#008200', 'gray']
20 os_order = ['linux', 'mac', 'win', 'otheros']
21 time_order = ['notime', 'little', 'most', 'always']
22 time_colors = ['#AA2029', '#D1942B', '#7FB142', '#69A7CE']
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     'other': '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         'psychophys': '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"]
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         kv = line.split(':')
95         d[kv[0]] = kv[1].strip().strip('"')
96     return d
97
98
99
100 class DB(dict):
101     os_dict = load_list2dict('oslist.txt')
102     datamod_dict = load_list2dict('datamodlist.txt')
103     sw_dict = load_list2dict('swlist.txt')
104     position_dict = load_list2dict('position-dd-list.txt')
105     employer_dict = load_list2dict('employer-dd-list.txt')
106
107     def __init__(self, srcdir):
108         # eats the whole directory
109         if srcdir is None:
110             return
111         datafilenames = glob('%s/*.json' % srcdir)
112         for dfn in datafilenames:
113             rawdata = jsonload(open(dfn))
114             self[rawdata['timestamp']] = rawdata
115
116     def get_unique(self, key):
117         # return a set of all (unique) values for a field id
118         uniq = set()
119         for d in self.values():
120             if key in d:
121                 el = d[key]
122                 if isinstance(el, list):
123                     uniq = uniq.union(el)
124                 else:
125                     uniq = uniq.union((el,))
126         return uniq
127
128     def get_not_none(self, key):
129         # return a list of all values of a specific field id
130         # the second return value is count of submission that did not have data
131         # for this field id
132         val = []
133         missing = 0
134         for d in self.values():
135             if key in d:
136                 el = d[key]
137                 if isinstance(el, list):
138                     val.extend(el)
139                 else:
140                     if el == 'none':
141                         missing += 1
142                     else:
143                         val.append(el)
144             else:
145                 missing += 1
146         return val, missing
147
148     def get_counts(self, key):
149         # return a dict with field values as keys and respective submission 
150         # count as value
151         vals = self.get_not_none(key)[0]
152         uniq = np.unique(vals)
153         counts = dict(zip(uniq, [vals.count(u) for u in uniq]))
154         return counts
155
156     def select_match(self, key, values):
157         # return a db with all submissions were a field id has one of the
158         # supplied values
159         match = DB(None)
160         for k, v in self.items():
161             if not key in v:
162                 continue
163             el = v[key]
164             if isinstance(el, list):
165                 if len(set(values).intersection(el)):
166                     match[k] = v
167             elif el in values:
168                 match[k] = v
169         return match
170
171     def get_nice_name(self, id):
172         srcs = [DB.os_dict, os_cat_names, DB.sw_dict, sw_categories,
173                 resource_categories, time_categories,
174                 DB.datamod_dict, DB.position_dict, DB.employer_dict]
175         for src in srcs:
176             if id in src:
177                 return src[id]
178         # not found, nothing nicer
179         return id
180
181
182 def mkpic_os_per_env(db, destdir):
183     envs = ['pers_os', 'man_os', 'virt_host_os', 'virt_guest_os']
184     env_names = ['Personal', 'Managed', 'Virt. Host', 'Virt. Guest']
185     env_stats = {}
186     for env in envs:
187         counts = db.get_counts(env)
188         stats = dict(zip(os_family.keys(), [0] * len(os_family)))
189         for os in counts:
190             stats[os_family_rev[os]] += counts[os]
191         total_count = np.sum(stats.values())
192         for osf in stats:
193             if not total_count:
194                 stats[osf] = 0
195             else:
196                 stats[osf] = float(stats[osf]) / total_count
197         env_stats[env] = stats
198     # make stacked barplot
199     pl.figure(figsize=(6.4, 4.8))
200     x = np.arange(len(envs))
201     bottoms = np.zeros(len(envs))
202     for i, os in enumerate(os_order):
203         stat = [env_stats[e][os] for e in envs]
204         pl.bar(x, stat, bottom=bottoms, color=os_colors[i],
205                label=db.get_nice_name(os), width=0.8)
206         bottoms += stat
207     pl.legend(loc='lower right')
208     pl.xticks(x + 0.4,  [db.get_nice_name(e) for e in env_names])
209     pl.xlim(-0.25, len(envs))
210     pl.title("Operating system preference by environment")
211     pl.ylabel("Fraction of submissions")
212     pl.savefig('%s/ospref_by_env.png' % destdir, format='png', dpi=80)
213
214
215 def mkpic_time_per_env(db, destdir):
216     envs = ['pers_time', 'man_time', 'virt_time']
217     env_names = ['Personal', 'Managed', 'Virtual']
218     env_stats = {}
219     for env in envs:
220         counts = dict(zip(time_order, [0] * len(time_order)))
221         counts.update(db.get_counts(env))
222         total_count = np.sum(counts.values())
223         for c in counts:
224             counts[c] = float(counts[c]) / total_count
225         env_stats[env] = counts
226     # make stacked barplot
227     pl.figure(figsize=(7.5, 4))
228     x = np.arange(len(envs))
229     bottoms = np.zeros(len(envs))
230     for i, t in enumerate(time_order):
231         stat = [env_stats[e][t] for e in envs]
232         pl.barh(x, stat, left=bottoms, color=time_colors[i],
233                label=db.get_nice_name(t), height=.6)
234         bottoms += stat
235     pl.legend(loc='center left')
236     pl.yticks(x + 0.2,  env_names)
237     pl.ylim(-0.4, len(envs))
238     pl.title("Research activity time by environment")
239     pl.xlabel("Fraction of submissions")
240     pl.savefig('%s/time_by_env.png' % destdir, format='png', dpi=80)
241
242
243 def mkpic_submissions_per_key(db, destdir, key, title, sortby='name',
244                             multiple=False):
245     counts = db.get_counts(key)
246     pl.figure(figsize=(6.4, 4.8))
247     pl.title(title)
248     if not len(counts):
249         pl.text(.5, .5, "[Insufficient data for this figure]",
250                 horizontalalignment='center')
251         pl.axis('off')
252     else:
253         # sort by name
254         if sortby == 'name':
255             stats = sorted(counts.items(), cmp=lambda x, y: cmp(x[0], y[0]))
256         elif sortby == 'count':
257             stats = sorted(counts.items(), cmp=lambda x, y: cmp(x[1], y[1]))[::-1]
258         else:
259             raise ValueError("Specify either name or count for sortby")
260         x = np.arange(len(stats))
261         pl.bar(x + (1./8), [s[1] for s in stats], width=0.75, color = '#008200')
262         pl.xticks(x + 0.5,  ['' for s in stats])
263         for i, s in enumerate(stats):
264             pl.text(i+.5, 0.1, db.get_nice_name(s[0]), rotation=90,
265                     horizontalalignment='center',
266                     verticalalignment='bottom',
267                     bbox=dict(facecolor='white', alpha=0.8, edgecolor='white'))
268         pl.xlim(0, len(stats))
269         yl = "Number of submissions"
270         if multiple:
271             yl += "\n(multiple choices per submission possible)"
272         pl.ylabel(yl)
273     pl.savefig('%s/submissions_per_%s.png' % (destdir, key), format='png', dpi=80)
274
275
276 def mkpic_resources(db, destdir):
277     res = db.get_counts('software_resource')
278     res = res.items()
279     x = np.arange(len(res))
280     pl.figure(figsize=(6.4, 4.8))
281     pl.title('Software resources')
282     pl.bar(x + (1./8), [s[1] for s in res], width=0.75, color = '#008200')
283     pl.xticks(x + 0.5,  ['' for s in res])
284     for i, s in enumerate(res):
285         pl.text(i+.5, 0.1, db.get_nice_name(s[0]), rotation=90,
286                 horizontalalignment='center',
287                 verticalalignment='bottom',
288                 bbox=dict(facecolor='white', alpha=0.8, edgecolor='white'))
289     pl.ylabel('Number of submissions')
290     pl.savefig('%s/software_resources.png' % destdir, format='png', dpi=80)
291
292 def mkpic_software(db, destdir):
293     for typ in sw_categories.keys():
294         mkpic_submissions_per_key(
295             db, destdir, 'sw_%s' % typ,
296             title="Software popularity: %s" % db.get_nice_name(typ),
297             sortby='name')
298
299 def mkpic_rating_by_os(db, env, items, destdir, title):
300     pl.figure(figsize=(6.4, 4.8))
301     for i, os in enumerate(os_order):
302         ratings = [db.select_match(env,
303                         os_family[os]).get_not_none('%s' % (it,))[0]
304                             for it in items]
305         plot_bars(ratings, offset=((i+1)*0.2)-0.1, color=os_colors[i],
306                   title=title, ylabel="Mean rating", label=db.get_nice_name(os))
307     pl.ylim((0,3))
308     pl.xlim((0,len(items)))
309     pl.yticks((0, 3), ['Disagree', 'Agree'], rotation=90)
310     pl.xticks(np.arange(len(items))+0.5, [i[-2:] for i in items],
311               horizontalalignment='center')
312     pl.legend(loc='lower right')
313     pl.savefig('%s/ratings_%s.png' % (destdir, env), format='png', dpi=80)
314
315
316 def main(srcdir, destdir):
317     db = DB(srcdir)
318     if not os.path.exists(destdir):
319         os.makedirs(destdir)
320
321     mkpic_submissions_per_key(
322         db, destdir, 'bg_datamod', sortby='count',
323         title='Submissions per data modality\n(multiple choices per submission possible)')
324
325     mkpic_submissions_per_key(
326         db, destdir, 'bg_position', title='Submissions per position', sortby='count')
327
328     mkpic_submissions_per_key(
329         db, destdir, 'bg_country', title='Submissions per country', sortby='count')
330
331     mkpic_submissions_per_key(
332         db, destdir, 'bg_employer', title='Submissions per venue', sortby='count')
333
334     for pic in [mkpic_os_per_env, mkpic_software,
335                 mkpic_resources, mkpic_time_per_env]:
336         pic(db, destdir)
337     mkpic_rating_by_os(db, 'pers_os', ['pers_r%i' % i for i in range(1, 9)], destdir,
338                        "Ratings: Personal environment")
339     mkpic_rating_by_os(db, 'man_os', ['man_r%i' % i for i in range(1, 5)], destdir,
340                        "Ratings: Managed environment")
341     mkpic_rating_by_os(db, 'virt_host_os', ['virt_r%i' % i for i in range(1, 4)], destdir,
342                        "Ratings: Virtual environment (by host OS)")
343     # submission stats: this is RST
344     statsfile = open('%s/stats.txt' % destdir, 'w')
345     statsfile.write('::\n\n  Number of submissions: %i\n' % len(db))
346     statsfile.write('  Statistics last updated: %s\n\n' \
347             % time.strftime('%A, %B %d %Y, %H:%M:%S UTC', time.gmtime()))
348     statsfile.close()
349
350 if __name__ == '__main__':
351     main(sys.argv[1], sys.argv[2])