]> git.donarmstrong.com Git - neurodebian.git/blob - survey/makestats
NF: parsing out those ratings questions
[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 = ['#AA2029', '#D1942B', '#7FB142', '#69A7CE']
20 os_order = ['linux', 'mac', 'win', 'otheros']
21 time_order = ['notime', 'little', 'most', 'always']
22 time_colors = ['#FF0000', '#FF5500', '#FFAC00', '#FFFD08']
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         if line.strip() == "":
95             continue
96         kv = line.split(':')
97         if kv[0] in d:
98             raise RuntimeError(
99                 "Got a line %s with a duplicate key %s whenever value for it "
100                 "is known already to be %r" % (line, kv[0], d[kv[0]]))
101         d[kv[0]] = kv[1].strip().strip('"')
102     return d
103
104
105
106 class DB(dict):
107     os_dict = load_list2dict('oslist.txt')
108     datamod_dict = load_list2dict('datamodlist.txt')
109     sw_dict = load_list2dict('swlist.txt')
110     position_dict = load_list2dict('position-dd-list.txt')
111     employer_dict = load_list2dict('employer-dd-list.txt')
112     ratings_dict = load_list2dict('ratingslist.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 get_nice_name(self, id):
179         srcs = [DB.os_dict, os_cat_names, DB.sw_dict, sw_categories,
180                 resource_categories, time_categories,
181                 DB.datamod_dict, DB.position_dict, DB.employer_dict]
182         for src in srcs:
183             if id in src:
184                 return src[id]
185         # not found, nothing nicer
186         return id
187
188
189 def mkpic_os_per_env(db, destdir):
190     envs = ['pers_os', 'man_os', 'virt_host_os', 'virt_guest_os']
191     env_names = ['Personal', 'Managed', 'Virt. Host', 'Virt. Guest']
192     env_stats = {}
193     for env in envs:
194         counts = db.get_counts(env)
195         stats = dict(zip(os_family.keys(), [0] * len(os_family)))
196         for os in counts:
197             stats[os_family_rev[os]] += counts[os]
198         total_count = np.sum(stats.values())
199         for osf in stats:
200             if not total_count:
201                 stats[osf] = 0
202             else:
203                 stats[osf] = float(stats[osf]) / total_count
204         env_stats[env] = stats
205     # make stacked barplot
206     pl.figure(figsize=(6.4, 4.8))
207     x = np.arange(len(envs))
208     bottoms = np.zeros(len(envs))
209     for i, os in enumerate(os_order):
210         stat = [env_stats[e][os] for e in envs]
211         pl.bar(x, stat, bottom=bottoms, color=os_colors[i],
212                label=db.get_nice_name(os), width=0.8)
213         bottoms += stat
214     pl.legend(loc='lower right')
215     pl.xticks(x + 0.4,  [db.get_nice_name(e) for e in env_names])
216     pl.xlim(-0.25, len(envs))
217     pl.title("Operating system preference by environment")
218     pl.ylabel("Fraction of submissions")
219     pl.savefig('%s/ospref_by_env.png' % destdir, format='png', dpi=80)
220
221
222 def mkpic_time_per_env(db, destdir):
223     envs = ['pers_time', 'man_time', 'virt_time']
224     env_names = ['Personal', 'Managed', 'Virtual']
225     env_stats = {}
226     for env in envs:
227         counts = dict(zip(time_order, [0] * len(time_order)))
228         counts.update(db.get_counts(env))
229         total_count = np.sum(counts.values())
230         for c in counts:
231             counts[c] = float(counts[c]) / total_count
232         env_stats[env] = counts
233     # make stacked barplot
234     pl.figure(figsize=(7.5, 4))
235     x = np.arange(len(envs))
236     bottoms = np.zeros(len(envs))
237     for i, t in enumerate(time_order):
238         stat = [env_stats[e][t] for e in envs]
239         pl.barh(x, stat, left=bottoms, color=time_colors[i],
240                label=db.get_nice_name(t), height=.6)
241         bottoms += stat
242     pl.legend(loc='center left')
243     pl.yticks(x + 0.2,  env_names)
244     pl.ylim(-0.4, len(envs))
245     pl.title("Research activity time by environment")
246     pl.xlabel("Fraction of submissions")
247     pl.subplots_adjust(right=0.97)
248     pl.savefig('%s/time_by_env.png' % destdir, format='png', dpi=80)
249
250
251 def mkpic_submissions_per_key(db, destdir, key, title, sortby='name',
252                             multiple=False):
253     counts = db.get_counts(key)
254     pl.figure(figsize=(6.4, (len(counts)-2) * 0.4 + 2))
255     tmargin = .8/len(counts)
256     if tmargin > 0.3: tmargin = 0.3
257     print key, tmargin
258     pl.subplots_adjust(left=0.03, right=0.97, top=1-tmargin, bottom=tmargin)
259     pl.title(title)
260     if not len(counts):
261         pl.text(.5, .5, "[Insufficient data for this figure]",
262                 horizontalalignment='center')
263         pl.axis('off')
264     else:
265         # sort by name
266         if sortby == 'name':
267             stats = sorted(counts.items(), cmp=lambda x, y: cmp(x[0], y[0]))
268         elif sortby == 'count':
269             stats = sorted(counts.items(), cmp=lambda x, y: cmp(x[1], y[1]))[::-1]
270         else:
271             raise ValueError("Specify either name or count for sortby")
272         x = np.arange(len(stats))
273         pl.barh(x + (1./8), [s[1] for s in stats], height=0.75, color = '#008200')
274         pl.yticks(x + 0.5,  ['' for s in stats])
275         for i, s in enumerate(stats):
276             pl.text(0.1, i+.5, db.get_nice_name(s[0]),
277                     horizontalalignment='left',
278                     verticalalignment='center',
279                     bbox=dict(facecolor='white', alpha=0.8, edgecolor='white'))
280         pl.ylim(0, len(stats))
281         yl = "Number of submissions"
282         if multiple:
283             yl += "\n(multiple choices per submission possible)"
284         pl.xlabel(yl)
285     pl.savefig('%s/submissions_per_%s.png' % (destdir, key), format='png', dpi=80)
286
287
288 def mkpic_resources(db, destdir):
289     res = db.get_counts('software_resource')
290     res = res.items()
291     x = np.arange(len(res))
292     pl.figure(figsize=(6.4, 4.8))
293     pl.title('Software resources')
294     pl.bar(x + (1./8), [s[1] for s in res], width=0.75, color = '#008200')
295     pl.xticks(x + 0.5,  ['' for s in res])
296     for i, s in enumerate(res):
297         pl.text(i+.5, 0.1, db.get_nice_name(s[0]), rotation=90,
298                 horizontalalignment='center',
299                 verticalalignment='bottom',
300                 bbox=dict(facecolor='white', alpha=0.8, edgecolor='white'))
301     pl.ylabel('Number of submissions')
302     pl.savefig('%s/software_resources.png' % destdir, format='png', dpi=80)
303
304 def mkpic_software(db, destdir):
305     for typ in sw_categories.keys():
306         mkpic_submissions_per_key(
307             db, destdir, 'sw_%s' % typ,
308             title="Software popularity: %s" % db.get_nice_name(typ),
309             sortby='name')
310
311 def mkpic_rating_by_os(db, env, items, destdir, title):
312     pl.figure(figsize=(6.4, 4.8))
313     for i, os in enumerate(os_order):
314         ratings = [db.select_match(env,
315                         os_family[os]).get_not_none('%s' % (it,))[0]
316                             for it in items]
317         plot_bars(ratings, offset=((i+1)*0.2)-0.1, color=os_colors[i],
318                   title=title, ylabel="Mean rating", label=db.get_nice_name(os))
319     pl.ylim((0,3))
320     pl.xlim((0,len(items)))
321     pl.yticks((0, 3), ['Disagree', 'Agree'], rotation=90)
322     pl.xticks(np.arange(len(items))+0.5, [i[-2:] for i in items],
323               horizontalalignment='center')
324     pl.legend(loc='lower right')
325     pl.savefig('%s/ratings_%s.png' % (destdir, env), format='png', dpi=80)
326
327
328 def main(srcdir, destdir):
329     db = DB(srcdir)
330     if not os.path.exists(destdir):
331         os.makedirs(destdir)
332
333     mkpic_submissions_per_key(
334         db, destdir, 'bg_datamod', sortby='count',
335         title='Submissions per data modality\n(multiple choices per submission possible)')
336
337     mkpic_submissions_per_key(
338         db, destdir, 'bg_position', title='Submissions per position', sortby='count')
339
340     mkpic_submissions_per_key(
341         db, destdir, 'bg_country', title='Submissions per country', sortby='count')
342
343     mkpic_submissions_per_key(
344         db, destdir, 'bg_employer', title='Submissions per venue', sortby='count')
345
346     for pic in [mkpic_os_per_env, mkpic_software,
347                 mkpic_resources, mkpic_time_per_env]:
348         pic(db, destdir)
349     mkpic_rating_by_os(db, 'pers_os', ['pers_r%i' % i for i in range(1, 9)], destdir,
350                        "Ratings: Personal environment")
351     mkpic_rating_by_os(db, 'man_os', ['man_r%i' % i for i in range(1, 5)], destdir,
352                        "Ratings: Managed environment")
353     mkpic_rating_by_os(db, 'virt_host_os', ['virt_r%i' % i for i in range(1, 4)], destdir,
354                        "Ratings: Virtual environment (by host OS)")
355     # submission stats: this is RST
356     statsfile = open('%s/stats.txt' % destdir, 'w')
357     statsfile.write('::\n\n  Number of submissions: %i\n' % len(db))
358     statsfile.write('  Statistics last updated: %s\n\n' \
359             % time.strftime('%A, %B %d %Y, %H:%M:%S UTC', time.gmtime()))
360     statsfile.close()
361
362 if __name__ == '__main__':
363     main(sys.argv[1], sys.argv[2])