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):
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]))
172 def select_match(self, key, values):
173 # return a db with all submissions were a field id has one of the
176 for k, v in self.items():
180 if isinstance(el, list):
181 if len(set(values).intersection(el)):
187 def select_match_exactly(self, key, values):
188 # return a db with all submissions were a field id has value
189 # equal to the supplied
191 set_values = set(values)
192 for k, v in self.items():
196 if isinstance(el, list):
197 if set(el) == set_values:
199 elif set([el]) == set_values:
203 def get_nice_name(self, id):
204 srcs = [DB.os_dict, os_cat_names, DB.sw_dict, sw_categories,
205 resource_categories, time_categories,
206 DB.datamod_dict, DB.position_dict, DB.employer_dict,
207 DB.vm_dict, DB.ratings_dict]
208 suffix = u'$^†$' if id in fresh_keys else ''
211 return src[id] + suffix
212 # not found, nothing nicer
216 def mkpic_os_per_env(db, destdir):
217 envs = ['pers_os', 'man_os', 'virt_host_os', 'virt_guest_os']
218 env_names = ['Personal', 'Managed', 'Virt. Host', 'Virt. Guest']
221 counts = db.get_counts(env)
222 stats = dict(zip(os_family.keys(), [0] * len(os_family)))
224 stats[os_family_rev[os]] += counts[os]
225 total_count = np.sum(stats.values())
230 stats[osf] = float(stats[osf]) / total_count
231 env_stats[env] = stats
232 # make stacked barplot
233 pl.figure(figsize=(7.5, 4))
234 x = np.arange(len(envs))
235 bottoms = np.zeros(len(envs))
236 for i, os in enumerate(os_order):
237 stat = [env_stats[e][os] for e in envs[::-1]]
238 pl.barh(x, stat, left=bottoms, color=os_colors[i],
239 label=db.get_nice_name(os), height=0.8)
241 pl.legend(loc='center left')
242 pl.yticks(x + 0.4, env_names[::-1])
243 pl.ylim(-0.25, len(envs))
245 pl.title("Operating system preference by environment")
246 pl.xlabel("Fraction of submissions")
247 pl.subplots_adjust(left=0.15, right=0.97)
248 pl.savefig('%s/ospref_by_env.png' % destdir, format='png', dpi=80)
251 def mkpic_time_per_env(db, destdir):
252 envs = ['pers_time', 'man_time', 'virt_time']
253 env_names = ['Personal', 'Managed', 'Virtual']
256 counts = dict(zip(time_order, [0] * len(time_order)))
257 counts.update(db.get_counts(env))
258 total_count = np.sum(counts.values())
260 counts[c] = float(counts[c]) / total_count
261 env_stats[env] = counts
262 # make stacked barplot
263 pl.figure(figsize=(7.5, 4))
264 x = np.arange(len(envs))
265 bottoms = np.zeros(len(envs))
266 for i, t in enumerate(time_order):
267 stat = [env_stats[e][t] for e in envs[::-1]]
268 pl.barh(x, stat, left=bottoms, color=time_colors[i],
269 label=db.get_nice_name(t), height=.6)
271 pl.legend(loc='lower left')
272 pl.yticks(x + 0.2, env_names[::-1])
273 pl.ylim(-0.4, len(envs))
274 pl.title("Research activity time by environment")
275 pl.xlabel("Fraction of submissions")
276 pl.subplots_adjust(right=0.97)
277 pl.savefig('%s/time_by_env.png' % destdir, format='png', dpi=80)
280 def mkpic_submissions_per_key(db, destdir, key, title, sortby='name',
282 counts = db.get_counts(key)
283 pl.figure(figsize=(6.4, (len(counts)-2) * 0.4 + 2))
284 if not len(counts): tmargin = 0.4
285 else: tmargin = .8/len(counts)
286 if tmargin > 0.3: tmargin = 0.3
287 pl.subplots_adjust(left=0.03, right=0.97, top=1-tmargin, bottom=tmargin)
290 pl.text(.5, .5, "[Insufficient data for this figure]",
291 horizontalalignment='center')
296 stats = sorted(counts.items(), cmp=lambda x, y: cmp(x[0], y[0]))
297 elif sortby == 'count':
298 stats = sorted(counts.items(), cmp=lambda x, y: cmp(x[1], y[1]))[::-1]
300 raise ValueError("Specify either name or count for sortby")
301 x = np.arange(len(stats))
302 pl.barh(x + (1./8), [s[1] for s in stats[::-1]], height=0.75, color = '#008200')
303 pl.yticks(x + 0.5, ['' for s in stats])
304 text_offset = pl.gca().get_xlim()[1] / 30.
305 for i, s in enumerate(stats[::-1]):
306 pl.text(text_offset, i+.5, db.get_nice_name(s[0]) + " [%d]" % (s[1],),
307 horizontalalignment='left',
308 verticalalignment='center',
309 bbox=dict(facecolor='white', alpha=0.8, edgecolor='white'))
310 pl.ylim(0, len(stats))
311 yl = "Number of submissions"
313 yl += "\n(multiple choices per submission possible)"
315 pl.savefig('%s/submissions_per_%s.png' % (destdir, key), format='png', dpi=80)
318 def mkpic_software(db, destdir):
319 for typ in sw_categories.keys():
320 mkpic_submissions_per_key(
321 db, destdir, 'sw_%s' % typ,
322 title="Software popularity: %s" % db.get_nice_name(typ),
325 def mkpic_rating_by_os(db, env, items, destdir, title):
326 from mvpa.misc.plot.base import plot_bars
328 pl.figure(figsize=(6.4, 4.8))
329 for i, os in enumerate(os_order):
330 ratings = [db.select_match(env,
331 os_family[os]).get_not_none('%s' % (it,))[0]
333 plot_bars(ratings, offset=((i+1)*0.2)-0.1, color=os_colors[i],
334 title=title, ylabel="Mean rating", label=db.get_nice_name(os))
336 pl.xlim((0,len(items)))
337 pl.yticks((0, 3), ['Disagree', 'Agree'], rotation=90)
338 pl.xticks(np.arange(len(items))+0.5, [i[-2:] for i in items],
339 horizontalalignment='center')
340 pl.legend(loc='lower right')
341 pl.savefig('%s/ratings_%s.png' % (destdir, env), format='png', dpi=80)
343 def mkpic_rating_by_os_hor_joined(db, env, items, destdir='.', title=None,
344 intro_sentence="I agree with the statements",
345 suffix='', max_rating=4):
347 #pl.figure(figsize=(6.4, 4.8))
348 if max_rating is None:
349 assert(len(items) == 1)
350 # We need to query for it
352 max_rating = np.max([db[k][field] for k in db if field in db[k]]) + 1
353 print "max ", max_rating
355 rst = open('figures/ratings_%s%s.rst' % (env, suffix), 'w')
366 """ % (title, '=' * len(title), intro_sentence))
367 for k, it in enumerate(items):
369 pl.figure(figsize=(3.2, 0.75))
371 pl.figure(figsize=(3.2, 0.5))
372 it_nice = db.get_nice_name(it)#.lstrip('.').lstrip(' ')
373 it_nice = it_nice[0].upper() + it_nice[1:]
374 for i, os in enumerate(os_order):
375 ratings = np.array(db.select_match(env,
376 os_family[os]).get_not_none('%s' % (it,))[0])
378 # assert(max(ratings) < max_rating)
379 # Complement with errorbar
381 scaling = float(per_os_width)/(max_rating-1)
382 meanstat = np.mean(ratings)
383 meanstat_point = scaling * meanstat
384 # standard error of estimate
385 errstat_point = len(ratings) > 1 and scaling*np.std(ratings)/np.sqrt(len(ratings)-1) or 0
386 #print ratings, meanstat, meanstat_point, errstat_point
388 # Beautiful piece not yet appreciated by the audience
391 max_rating_max = max(max_rating, max(ratings)+1)
392 for r in sorted(set(ratings)):#range(max_rating_max):
393 stat = np.sum(ratings == r) * meanstat_point / float(total)
394 #print r, it, os, stat, total
395 #if it == "pers_r8" and os == "linux" and r == 3:
396 # import pydb; pydb.debugger()
397 kwargs = dict(label=None)
399 pl.barh(1.0/nos * (nos - 1 - i), stat, left=bottom, color=os_colors[i],
400 height=.25, alpha=1./max_rating_max + r/float(max_rating_max),
402 edgecolor=os_colors[i])
405 pl.barh(1.0/nos * (nos - 1 - i), meanstat_point, left=0,
406 color=os_colors[i], height=.25, alpha=1.0, label=None)
407 pl.errorbar([meanstat_point],
408 [1.0/nos * (nos - 0.5 - i)],
409 xerr=[errstat_point], fmt='o', color=os_colors[i], ecolor='k')
410 pl.xlim((0, per_os_width))
411 if k == 0 and max_rating == 4: # ad-hoc: only for those disagree/agree
412 pl.text(0, 1.1, "Disagree", horizontalalignment='left')
413 pl.text(per_os_width, 1.1, "Agree", horizontalalignment='right')
418 pl.subplots_adjust(left=0.00, right=1., bottom=0.0, top=1,
419 wspace=0.05, hspace=0.05)
420 fname = '%s/ratings_%s_%s%s.png' % (destdir, env, it, suffix)
421 pl.savefig(fname, format='png', dpi=80)
423 oddrow_s = k % 2 == 0 and ' class="oddrow"' or ''
427 <td><img border="0" alt="%(fname)s" src="%(fname)s" /></td> </tr>"""
438 def main(srcdir, destdir):
441 ## Plot maintenance time per each group
442 # assess what would be our range
443 pmts, _ = db.get_not_none('pers_maint_time')
444 max_rating = int(np.mean(pmts) + np.std(pmts))
445 for pos in db.get_unique('bg_position'):
447 mkpic_rating_by_os_hor_joined(db.select_match('bg_position', pos),
448 'pers_os', ['pers_maint_time'], destdir,
449 "Personal environment", "", suffix='_maint_time_%s' % pos,
450 max_rating=max_rating)
453 # custom selection for people dealing more with hardware
455 ## db = db2.select_match('bg_datamod', (('ephys'),))
456 # or only selected ones (so no fmri/pet etc)
457 ## db = db2.select_match_exactly('bg_datamod', (('ephys'), ('behav'),))
458 ## db.update(db2.select_match_exactly('bg_datamod', (('ephys'),)))
459 ## db.update(db2.select_match_exactly('bg_datamod', (('ephys'), ('genetic'),)))
460 ## db.update(db2.select_match_exactly('bg_datamod', (('ephys'), ('simulation'),)))
461 ## db.update(db2.select_match_exactly('bg_datamod', (('ephys'), ('meeg'),)))
463 if not os.path.exists(destdir):
466 mkpic_submissions_per_key(
467 db, destdir, 'virt_prod', sortby='count',
468 title='Virtualization product popularity')
470 mkpic_submissions_per_key(
471 db, destdir, 'bg_datamod', sortby='count',
472 title='Submissions per data modality')
474 mkpic_submissions_per_key(
475 db, destdir, 'bg_position', title='Submissions per position', sortby='count')
477 mkpic_submissions_per_key(
478 db, destdir, 'bg_country', title='Submissions per country', sortby='count')
480 mkpic_submissions_per_key(
481 db, destdir, 'bg_employer', title='Submissions per venue', sortby='count')
483 mkpic_submissions_per_key(
484 db, destdir, 'software_resource', title='Software resource popularity', sortby='count')
486 for pic in [mkpic_os_per_env, mkpic_software, mkpic_time_per_env]:
490 mkpic_rating_by_os_hor_joined(db, 'pers_os', ['pers_r%i' % i for i in range(1, 9)], destdir,
491 "Personal environment", "I prefer this particular scientific software environment because ...")
492 mkpic_rating_by_os_hor_joined(db, 'man_os', ['man_r%i' % i for i in range(1, 6)], destdir,
493 "Managed environment")
494 mkpic_rating_by_os_hor_joined(db, 'virt_host_os', ['virt_r%i' % i for i in range(1, 5)], destdir,
495 "Virtual environment (by host OS)")
496 mkpic_rating_by_os_hor_joined(db, 'virt_guest_os', ['virt_r%i' % i for i in range(1, 5)], destdir,
497 "Virtual environment (by guest OS)")
499 ## mkpic_rating_by_os_hor_joined(db.select_match('virt_prod', (('vmware'),)),
500 ## 'virt_host_os', ['virt_r%i' % i for i in range(1, 5)], destdir,
501 ## "Virtualbox virtual environment (by host OS)")
503 # submission stats: this is RST
504 statsfile = open('%s/stats.txt' % destdir, 'w')
505 statsfile.write('::\n\n Number of submissions: %i\n' % len(db))
506 statsfile.write(' Statistics last updated: %s\n\n' \
507 % time.strftime('%A, %B %d %Y, %H:%M:%S UTC', time.gmtime()))
510 if __name__ == '__main__':
511 main(sys.argv[1], sys.argv[2])
512 #main('dataout', 'figures')