2 # emacs: -*- coding: utf-8; mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
6 from json import load as jload
10 from json import read as jread
12 return jread(f.read())
18 from common import entries_to_refresh
21 reduce(list.__add__,[x.items()
22 for x in entries_to_refresh['sw_other_name'].values()],
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']
32 'notime': "don't use it",
33 'little': "less than 50%",
34 'most': "more than 50%",
38 resource_categories = {
39 'vendor': 'Vendor/Project website',
40 'retailer': 'Retailer',
41 'os': 'Operating system',
46 'freebsdports': 'FreeBSD ports',
48 'macports': 'Macports',
49 'matlabcentral': 'Matlab Central',
50 'neurodebian': 'NeuroDebian',
53 'pythonbundles': 'Python bundles',
54 'sourceforge': 'Sourceforge',
55 'otherres': 'Other resource'
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'
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"]
88 'linux': redhat_family + debian_family + suse_family + other_linux_family,
89 'otheros': other_family
91 # end the reverse mapping
94 for os_ in os_family[ost]:
95 os_family_rev[os_] = ost
98 def load_list2dict(name):
102 if line.strip() == "":
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('"')
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')
123 def __init__(self, srcdir):
124 # eats the whole directory
127 datafilenames = glob('%s/*.json' % srcdir)
128 for dfn in datafilenames:
129 rawdata = jsonload(open(dfn))
130 self[rawdata['timestamp']] = rawdata
132 def get_unique(self, key):
133 # return a set of all (unique) values for a field id
135 for d in self.values():
138 if isinstance(el, list):
139 uniq = uniq.union(el)
141 uniq = uniq.union((el,))
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
150 for d in self.values():
153 if isinstance(el, list):
164 def get_counts(self, key, predef_keys=None):
165 # return a dict with field values as keys and respective submission
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)))
177 def select_match(self, key, values):
178 # return a db with all submissions were a field id has one of the
181 for k, v in self.items():
185 if isinstance(el, list):
186 if len(set(values).intersection(el)):
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
196 set_values = set(values)
197 for k, v in self.items():
201 if isinstance(el, list):
202 if set(el) == set_values:
204 elif set([el]) == set_values:
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 ''
216 return src[id] + suffix
217 # not found, nothing nicer
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']
226 counts = db.get_counts(env)
227 stats = dict(zip(os_family.keys(), [0] * len(os_family)))
229 stats[os_family_rev[os]] += counts[os]
230 total_count = np.sum(stats.values())
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)
246 pl.legend(loc='center left')
247 pl.yticks(x + 0.4, env_names[::-1])
248 pl.ylim(-0.25, len(envs))
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)
256 def mkpic_time_per_env(db, destdir):
257 envs = ['pers_time', 'man_time', 'virt_time']
258 env_names = ['Personal', 'Managed', 'Virtual']
261 counts = dict(zip(time_order, [0] * len(time_order)))
262 counts.update(db.get_counts(env))
263 total_count = np.sum(counts.values())
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)
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)
285 def mkpic_submissions_per_key(db, destdir, key, title, sortby='name',
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)
295 pl.text(.5, .5, "[Insufficient data for this figure]",
296 horizontalalignment='center')
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]
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"
318 yl += "\n(multiple choices per submission possible)"
320 pl.savefig('%s/submissions_per_%s.png' % (destdir, key), format='png', dpi=80)
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),
330 def mkpic_rating_by_os(db, env, items, destdir, title):
331 from mvpa.misc.plot.base import plot_bars
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]
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))
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)
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):
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
357 max_rating = np.max([db[k][field] for k in db if field in db[k]]) + 1
358 print "max ", max_rating
360 rst = open('figures/ratings_%s%s.rst' % (env, suffix), 'w')
371 """ % (title, '=' * len(title), intro_sentence))
372 for k, it in enumerate(items):
374 pl.figure(figsize=(3.2, 0.75))
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])
383 # assert(max(ratings) < max_rating)
384 # Complement with errorbar
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
393 # Beautiful piece not yet appreciated by the audience
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)
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),
407 edgecolor=os_colors[i])
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')
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)
428 oddrow_s = k % 2 == 0 and ' class="oddrow"' or ''
432 <td><img border="0" alt="%(fname)s" src="%(fname)s" /></td> </tr>"""
443 def main(srcdir, destdir):
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'):
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)
458 # custom selection for people dealing more with hardware
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'),)))
468 if not os.path.exists(destdir):
471 mkpic_submissions_per_key(
472 db, destdir, 'virt_prod', sortby='count',
473 title='Virtualization product popularity')
475 mkpic_submissions_per_key(
476 db, destdir, 'bg_datamod', sortby='count',
477 title='Submissions per data modality')
479 mkpic_submissions_per_key(
480 db, destdir, 'bg_position', title='Submissions per position', sortby='count')
482 mkpic_submissions_per_key(
483 db, destdir, 'bg_country', title='Submissions per country', sortby='count')
485 mkpic_submissions_per_key(
486 db, destdir, 'bg_employer', title='Submissions per venue', sortby='count')
488 mkpic_submissions_per_key(
489 db, destdir, 'software_resource', title='Software resource popularity', sortby='count')
491 for pic in [mkpic_os_per_env, mkpic_software, mkpic_time_per_env]:
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)")
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)")
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()))
515 if __name__ == '__main__':
516 main(sys.argv[1], sys.argv[2])
517 #main('dataout', 'figures')