]> git.donarmstrong.com Git - neurodebian.git/blob - survey/makestats
provide human-readable descriptions for positions and employer (venue)
[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 # resources
22 resource_categories = {
23     'vendor': 'Vendor/Project website',
24     'retailer': 'Retailer',
25     'os': 'Operating system',
26     'cpan': 'CPAN',
27     'cran': 'CRAN',
28     'epel': 'EPEL',
29     'fink': 'Fink',
30     'freebsdports': 'FreeBSD ports',
31     'incf': 'INCF',
32     'macports': 'Macports',
33     'matlabcentral': 'Matlab Central',
34     'neurodebian': 'NeuroDebian',
35     'nitrc': 'NITRC',
36     'pypi': 'PyPi',
37     'pythonbundles': 'Python bundles',
38     'sourceforge': 'Sourceforge',
39     'other': 'Other resource'
40     }
41 # software categories
42 sw_categories = {
43         'general': 'General computing',
44         'dc': 'Distributed computing',
45         'img': 'Brain imaging',
46         'datamanage': 'Data management',
47         'neusys': 'Neural systems modeling',
48         'electro': 'Electrophysiology, MEG/EEG',
49         'bci': 'Brain-computer interface',
50         'acq': 'Hardware interface/Data acquisition',
51         'rt': 'Real-time solutions',
52         'psychophys': 'Psychophysics/Experiment control'
53         }
54
55 # some meaningful groups of OSes
56 redhat_family = ["rhel", "centos", "fedora", "scilinux"]
57 debian_family = ["debian", "ubuntu", "biolinux"]
58 suse_family = ["suse", "slel"]
59 other_linux_family = ["gentoo", "mandriva", "arch", "slackware", "otherlinux"]
60 other_family = ["starbsd", "unix", "qnx", "beos", "solaris", "other"]
61
62 os_cat_names = {
63         'win': 'Windows',
64         'mac': 'Mac OS',
65         'linux': 'GNU/Linux',
66         'otheros': 'Other OS'
67         }
68
69 os_family = {
70         'win': ["windows"],
71         'mac': ["macosx"],
72         'linux': redhat_family + debian_family + suse_family + other_linux_family,
73         'otheros': other_family
74         }
75 # end the reverse mapping
76 os_family_rev = {}
77 for ost in os_family:
78     for os_ in os_family[ost]:
79         os_family_rev[os_] = ost
80
81
82 def load_list2dict(name):
83     d = {}
84     lfile = open(name)
85     for line in lfile:
86         kv = line.split(':')
87         d[kv[0]] = kv[1].strip().strip('"')
88     return d
89
90
91
92 class DB(dict):
93     os_dict = load_list2dict('oslist.txt')
94     datamod_dict = load_list2dict('datamodlist.txt')
95     sw_dict = load_list2dict('swlist.txt')
96     position_dict = load_list2dict('position-dd-list.txt')
97     employer_dict = load_list2dict('employer-dd-list.txt')
98
99     def __init__(self, srcdir):
100         # eats the whole directory
101         if srcdir is None:
102             return
103         datafilenames = glob('%s/*.json' % srcdir)
104         for dfn in datafilenames:
105             rawdata = jsonload(open(dfn))
106             self[rawdata['timestamp']] = rawdata
107
108     def get_unique(self, key):
109         # return a set of all (unique) values for a field id
110         uniq = set()
111         for d in self.values():
112             if key in d:
113                 el = d[key]
114                 if isinstance(el, list):
115                     uniq = uniq.union(el)
116                 else:
117                     uniq = uniq.union((el,))
118         return uniq
119
120     def get_not_none(self, key):
121         # return a list of all values of a specific field id
122         # the second return value is count of submission that did not have data
123         # for this field id
124         val = []
125         missing = 0
126         for d in self.values():
127             if key in d:
128                 el = d[key]
129                 if isinstance(el, list):
130                     val.extend(el)
131                 else:
132                     if el == 'none':
133                         missing += 1
134                     else:
135                         val.append(el)
136             else:
137                 missing += 1
138         return val, missing
139
140     def get_counts(self, key):
141         # return a dict with field values as keys and respective submission 
142         # count as value
143         vals = self.get_not_none(key)[0]
144         uniq = np.unique(vals)
145         counts = dict(zip(uniq, [vals.count(u) for u in uniq]))
146         return counts
147
148     def select_match(self, key, values):
149         # return a db with all submissions were a field id has one of the
150         # supplied values
151         match = DB(None)
152         for k, v in self.items():
153             if not key in v:
154                 continue
155             el = v[key]
156             if isinstance(el, list):
157                 if len(set(values).intersection(el)):
158                     match[k] = v
159             elif el in values:
160                 match[k] = v
161         return match
162
163     def get_nice_name(self, id):
164         srcs = [DB.os_dict, os_cat_names, DB.sw_dict, sw_categories,
165                 resource_categories, DB.datamod_dict, DB.position_dict,
166                 DB.employer_dict]
167         for src in srcs:
168             if id in src:
169                 return src[id]
170         # not found, nothing nicer
171         return id
172
173
174 def mkpic_os_per_env(db, destdir):
175     envs = ['pers_os', 'man_os', 'virt_host_os', 'virt_guest_os']
176     env_names = ['Personal', 'Managed', 'Virt. Host', 'Virt. Guest']
177     env_stats = {}
178     offset = 0
179     for env in envs:
180         counts = db.get_counts(env)
181         stats = dict(zip(os_family.keys(), [0] * len(os_family)))
182         for os in counts:
183             stats[os_family_rev[os]] += counts[os]
184         total_count = np.sum(stats.values())
185         for osf in stats:
186             stats[osf] = float(stats[osf]) / total_count
187         env_stats[env] = stats
188     # make stacked barplot
189     pl.figure(figsize=(6.4, 4.8))
190     x = np.arange(len(envs))
191     bottoms = np.zeros(len(envs))
192     for i, os in enumerate(os_order):
193         stat = [env_stats[e][os] for e in envs]
194         pl.bar(x, stat, bottom=bottoms, color=os_colors[i],
195                label=db.get_nice_name(os), width=0.8)
196         bottoms += stat
197     pl.legend(loc='lower right')
198     pl.xticks(x + 0.4,  [db.get_nice_name(e) for e in env_names])
199     pl.xlim(-0.25, len(envs))
200     pl.title("Operating system preference by environment")
201     pl.ylabel("Fraction of submissions")
202     pl.savefig('%s/ospref_by_env.png' % destdir, format='png', dpi=80)
203
204
205 def mkpic_submissions_per_key(db, destdir, key, title, sortby='name',
206                             multiple=False):
207     counts = db.get_counts(key)
208     pl.figure(figsize=(6.4, 4.8))
209     pl.title(title)
210     if not len(counts):
211         pl.text(.5, .5, "[Insufficient data for this figure]",
212                 horizontalalignment='center')
213         pl.axis('off')
214     else:
215         # sort by name
216         if sortby == 'name':
217             stats = sorted(counts.items(), cmp=lambda x, y: cmp(x[0], y[0]))
218         elif sortby == 'count':
219             stats = sorted(counts.items(), cmp=lambda x, y: cmp(x[1], y[1]))[::-1]
220         else:
221             raise ValueError("Specify either name or count for sortby")
222         x = np.arange(len(stats))
223         pl.bar(x + (1./8), [s[1] for s in stats], width=0.75, color = '#008200')
224         pl.xticks(x + 0.5,  ['' for s in stats])
225         for i, s in enumerate(stats):
226             pl.text(i+.5, 0.1, db.get_nice_name(s[0]), rotation=90,
227                     horizontalalignment='center',
228                     verticalalignment='bottom',
229                     bbox=dict(facecolor='white', alpha=0.8, edgecolor='white'))
230         pl.xlim(0, len(stats))
231         yl = "Number of submissions"
232         if multiple:
233             yl += "\n(multiple choices per submission possible)"
234         pl.ylabel(yl)
235     pl.savefig('%s/submissions_per_%s.png' % (destdir, key), format='png', dpi=80)
236
237
238 def mkpic_resources(db, destdir):
239     res = db.get_counts('software_resource')
240     res = res.items()
241     x = np.arange(len(res))
242     pl.figure(figsize=(6.4, 4.8))
243     pl.title('Software resources')
244     pl.bar(x + (1./8), [s[1] for s in res], width=0.75, color = '#008200')
245     pl.xticks(x + 0.5,  ['' for s in res])
246     for i, s in enumerate(res):
247         pl.text(i+.5, 0.1, db.get_nice_name(s[0]), rotation=90,
248                 horizontalalignment='center',
249                 verticalalignment='bottom',
250                 bbox=dict(facecolor='white', alpha=0.8, edgecolor='white'))
251     pl.ylabel('Number of submissions')
252     pl.savefig('%s/software_resources.png' % destdir, format='png', dpi=80)
253
254 def mkpic_software(db, destdir):
255     for typ in sw_categories.keys():
256         mkpic_submissions_per_key(
257             db, destdir, 'sw_%s' % typ,
258             title="Software popularity: %s" % db.get_nice_name(typ),
259             sortby='name')
260
261 def mkpic_rating_by_os(db, env, items, destdir, title):
262     pl.figure(figsize=(6.4, 4.8))
263     for i, os in enumerate(os_order):
264         ratings = [db.select_match(env,
265                         os_family[os]).get_not_none('%s' % (it,))[0]
266                             for it in items]
267         plot_bars(ratings, offset=((i+1)*0.2)-0.1, color=os_colors[i],
268                   title=title, ylabel="Mean rating", label=db.get_nice_name(os))
269     pl.ylim((0,3))
270     pl.xlim((0,len(items)))
271     pl.yticks((0, 3), ['Disagree', 'Agree'], rotation=90)
272     pl.xticks(np.arange(len(items))+0.5, [i[-2:] for i in items],
273               horizontalalignment='center')
274     pl.legend(loc='lower right')
275     pl.savefig('%s/ratings_%s.png' % (destdir, env), format='png', dpi=80)
276
277
278 def main(srcdir, destdir):
279     db = DB(srcdir)
280     if not os.path.exists(destdir):
281         os.makedirs(destdir)
282
283     mkpic_submissions_per_key(
284         db, destdir, 'bg_datamod', sortby='count',
285         title='Submissions per data modality\n(multiple choices per submission possible)')
286
287     mkpic_submissions_per_key(
288         db, destdir, 'bg_position', title='Submissions per position', sortby='count')
289
290     mkpic_submissions_per_key(
291         db, destdir, 'bg_country', title='Submissions per country', sortby='count')
292
293     mkpic_submissions_per_key(
294         db, destdir, 'bg_employer', title='Submissions per venue', sortby='count')
295
296     for pic in [mkpic_os_per_env, mkpic_software,
297                 mkpic_resources]:
298         pic(db, destdir)
299     mkpic_rating_by_os(db, 'pers_os', ['pers_r%i' % i for i in range(1, 9)], destdir,
300                        "Ratings: Personal environment")
301     mkpic_rating_by_os(db, 'man_os', ['man_r%i' % i for i in range(1, 5)], destdir,
302                        "Ratings: Managed environment")
303     mkpic_rating_by_os(db, 'virt_host_os', ['virt_r%i' % i for i in range(1, 4)], destdir,
304                        "Ratings: Virtual environment (by host OS)")
305     # submission stats: this is RST
306     statsfile = open('%s/stats.txt' % destdir, 'w')
307     statsfile.write('::\n\n  Number of submissions: %i\n' % len(db))
308     statsfile.write('  Statistics last updated: %s\n\n' \
309             % time.strftime('%A, %B %d %Y, %H:%M:%S UTC', time.gmtime()))
310     statsfile.close()
311
312 if __name__ == '__main__':
313     main(sys.argv[1], sys.argv[2])