]> git.donarmstrong.com Git - neurodebian.git/blobdiff - survey/makestats
Fix div by zero prob.
[neurodebian.git] / survey / makestats
index 776ab7a8b2221c7e192d7f1aba300a6bc8f9038b..09b0c9415b20fe6d7f39a554c2c836dc841cfa7d 100755 (executable)
 #!/usr/bin/python
 
+from mvpa.misc.plot.base import plot_bars
 from glob import glob
-import json
-import sys
+try:
+    from json import load as jload
+    def jsonload(f):
+        return jload(f)
+except ImportError:
+    from json import read as jread
+    def jsonload(f):
+        return jread(f.read())
+import sys, os
 import pylab as pl
 import numpy as np
+import time
+
+# uniform colors for OS results
+os_colors = ['#B63537', '#4E4DA0', '#008200', 'gray']
+os_order = ['linux', 'mac', 'win', 'otheros']
+time_order = ['notime', 'little', 'most', 'always']
+time_colors = ['#AA2029', '#D1942B', '#7FB142', '#69A7CE']
+time_categories = {
+        'notime': "don't use it",
+        'little': "less than 50%",
+        'most': "more than 50%",
+        'always': "always"
+        }
+# resources
+resource_categories = {
+    'vendor': 'Vendor/Project website',
+    'retailer': 'Retailer',
+    'os': 'Operating system',
+    'cpan': 'CPAN',
+    'cran': 'CRAN',
+    'epel': 'EPEL',
+    'fink': 'Fink',
+    'freebsdports': 'FreeBSD ports',
+    'incf': 'INCF',
+    'macports': 'Macports',
+    'matlabcentral': 'Matlab Central',
+    'neurodebian': 'NeuroDebian',
+    'nitrc': 'NITRC',
+    'pypi': 'PyPi',
+    'pythonbundles': 'Python bundles',
+    'sourceforge': 'Sourceforge',
+    'other': 'Other resource'
+    }
+# software categories
+sw_categories = {
+        'general': 'General computing',
+        'dc': 'Distributed computing',
+        'img': 'Brain imaging',
+        'datamanage': 'Data management',
+        'neusys': 'Neural systems modeling',
+        'electro': 'Electrophysiology, MEG/EEG',
+        'bci': 'Brain-computer interface',
+        'acq': 'Hardware interface/Data acquisition',
+        'rt': 'Real-time solutions',
+        'psychophys': 'Psychophysics/Experiment control'
+        }
+
+# some meaningful groups of OSes
+redhat_family = ["rhel", "centos", "fedora", "scilinux"]
+debian_family = ["debian", "ubuntu", "biolinux"]
+suse_family = ["suse", "slel"]
+other_linux_family = ["gentoo", "mandriva", "arch", "slackware", "otherlinux"]
+other_family = ["starbsd", "unix", "qnx", "beos", "solaris", "other"]
+
+os_cat_names = {
+        'win': 'Windows',
+        'mac': 'Mac OS',
+        'linux': 'GNU/Linux',
+        'otheros': 'Other OS'
+        }
+
+os_family = {
+        'win': ["windows"],
+        'mac': ["macosx"],
+        'linux': redhat_family + debian_family + suse_family + other_linux_family,
+        'otheros': other_family
+        }
+# end the reverse mapping
+os_family_rev = {}
+for ost in os_family:
+    for os_ in os_family[ost]:
+        os_family_rev[os_] = ost
+
+
+def load_list2dict(name):
+    d = {}
+    lfile = open(name)
+    for line in lfile:
+        kv = line.split(':')
+        d[kv[0]] = kv[1].strip().strip('"')
+    return d
+
+
 
 class DB(dict):
+    os_dict = load_list2dict('oslist.txt')
+    datamod_dict = load_list2dict('datamodlist.txt')
+    sw_dict = load_list2dict('swlist.txt')
+
     def __init__(self, srcdir):
         # eats the whole directory
+        if srcdir is None:
+            return
         datafilenames = glob('%s/*.json' % srcdir)
         for dfn in datafilenames:
-            rawdata = json.load(open(dfn))
+            rawdata = jsonload(open(dfn))
             self[rawdata['timestamp']] = rawdata
 
     def get_unique(self, key):
@@ -57,7 +154,7 @@ class DB(dict):
     def select_match(self, key, values):
         # return a db with all submissions were a field id has one of the
         # supplied values
-        match = {}
+        match = DB(None)
         for k, v in self.items():
             if not key in v:
                 continue
@@ -69,32 +166,183 @@ class DB(dict):
                 match[k] = v
         return match
 
+    def get_nice_name(self, id):
+        srcs = [DB.os_dict, os_cat_names, DB.sw_dict, sw_categories,
+                resource_categories, time_categories, DB.datamod_dict]
+        for src in srcs:
+            if id in src:
+                return src[id]
+        # not found, nothing nicer
+        return id
 
 
-def load_list2dict(name):
-    d = {}
-    lfile = open(name)
-    for line in lfile:
-        kv = line.split(':')
-        d[kv[0]] = kv[1].strip().strip('"')
-    return d
+def mkpic_os_per_env(db, destdir):
+    envs = ['pers', 'man', 'virt', 'virt']
+    env_names = ['Personal', 'Managed', 'Virt. Host', 'Virt. Guest']
+    env_stats = {}
+    for env in envs:
+        counts = db.get_counts(env)
+        stats = dict(zip(os_family.keys(), [0] * len(os_family)))
+        for os in counts:
+            stats[os_family_rev[os]] += counts[os]
+        total_count = np.sum(stats.values())
+        for osf in stats:
+            if not total_count:
+                stats[osf] = 0
+            else:
+                stats[osf] = float(stats[osf]) / total_count
+        env_stats[env] = stats
+    # make stacked barplot
+    pl.figure(figsize=(6.4, 4.8))
+    x = np.arange(len(envs))
+    bottoms = np.zeros(len(envs))
+    for i, os in enumerate(os_order):
+        stat = [env_stats[e][os] for e in envs]
+        pl.bar(x, stat, bottom=bottoms, color=os_colors[i],
+               label=db.get_nice_name(os), width=0.8)
+        bottoms += stat
+    pl.legend(loc='lower right')
+    pl.xticks(x + 0.4,  [db.get_nice_name(e) for e in env_names])
+    pl.xlim(-0.25, len(envs))
+    pl.title("Operating system preference by environment")
+    pl.ylabel("Fraction of submissions")
+    pl.savefig('%s/ospref_by_env.png' % destdir, format='png', dpi=80)
+
+
+def mkpic_time_per_env(db, destdir):
+    envs = ['pers_time', 'man_time', 'virt_time']
+    env_names = ['Personal', 'Managed', 'Virtual']
+    env_stats = {}
+    for env in envs:
+        counts = dict(zip(time_order, [0] * len(time_order)))
+        counts.update(db.get_counts(env))
+        total_count = np.sum(counts.values())
+        for c in counts:
+            counts[c] = float(counts[c]) / total_count
+        env_stats[env] = counts
+    # make stacked barplot
+    pl.figure(figsize=(7.5, 4))
+    x = np.arange(len(envs))
+    bottoms = np.zeros(len(envs))
+    for i, t in enumerate(time_order):
+        stat = [env_stats[e][t] for e in envs]
+        pl.barh(x, stat, left=bottoms, color=time_colors[i],
+               label=db.get_nice_name(t), height=.6)
+        bottoms += stat
+    pl.legend(loc='center left')
+    pl.yticks(x + 0.2,  env_names)
+    pl.ylim(-0.4, len(envs))
+    pl.title("Research activity time by environment")
+    pl.xlabel("Fraction of submissions")
+    pl.savefig('%s/ospref_by_env.png' % destdir, format='png', dpi=80)
+
+
+def mkpic_submissions_per_key(db, destdir, key, title, sortby='name',
+                            multiple=False):
+    counts = db.get_counts(key)
+    pl.figure(figsize=(6.4, 4.8))
+    pl.title(title)
+    if not len(counts):
+        pl.text(.5, .5, "[Insufficient data for this figure]",
+                horizontalalignment='center')
+        pl.axis('off')
+    else:
+        # sort by name
+        if sortby == 'name':
+            stats = sorted(counts.items(), cmp=lambda x, y: cmp(x[0], y[0]))
+        elif sortby == 'count':
+            stats = sorted(counts.items(), cmp=lambda x, y: cmp(x[1], y[1]))[::-1]
+        else:
+            raise ValueError("Specify either name or count for sortby")
+        x = np.arange(len(stats))
+        pl.bar(x + (1./8), [s[1] for s in stats], width=0.75, color = '#008200')
+        pl.xticks(x + 0.5,  ['' for s in stats])
+        for i, s in enumerate(stats):
+            pl.text(i+.5, 0.1, db.get_nice_name(s[0]), rotation=90,
+                    horizontalalignment='center',
+                    verticalalignment='bottom',
+                    bbox=dict(facecolor='white', alpha=0.8, edgecolor='white'))
+        pl.xlim(0, len(stats))
+        yl = "Number of submissions"
+        if multiple:
+            yl += "\n(multiple choices per submission possible)"
+        pl.ylabel(yl)
+    pl.savefig('%s/submissions_per_%s.png' % (destdir, key), format='png', dpi=80)
+
+
+def mkpic_resources(db, destdir):
+    res = db.get_counts('software_resource')
+    res = res.items()
+    x = np.arange(len(res))
+    pl.figure(figsize=(6.4, 4.8))
+    pl.title('Software resources')
+    pl.bar(x + (1./8), [s[1] for s in res], width=0.75, color = '#008200')
+    pl.xticks(x + 0.5,  ['' for s in res])
+    for i, s in enumerate(res):
+        pl.text(i+.5, 0.1, db.get_nice_name(s[0]), rotation=90,
+                horizontalalignment='center',
+                verticalalignment='bottom',
+                bbox=dict(facecolor='white', alpha=0.8, edgecolor='white'))
+    pl.ylabel('Number of submissions')
+    pl.savefig('%s/software_resources.png' % destdir, format='png', dpi=80)
+
+def mkpic_software(db, destdir):
+    for typ in sw_categories.keys():
+        mkpic_submissions_per_key(
+            db, destdir, 'sw_%s' % typ,
+            title="Software popularity: %s" % db.get_nice_name(typ),
+            sortby='name')
+
+def mkpic_rating_by_os(db, env, items, destdir, title):
+    pl.figure(figsize=(6.4, 4.8))
+    for i, os in enumerate(os_order):
+        ratings = [db.select_match(env,
+                        os_family[os]).get_not_none('%s' % (it,))[0]
+                            for it in items]
+        plot_bars(ratings, offset=((i+1)*0.2)-0.1, color=os_colors[i],
+                  title=title, ylabel="Mean rating", label=db.get_nice_name(os))
+    pl.ylim((0,3))
+    pl.xlim((0,len(items)))
+    pl.yticks((0, 3), ['Disagree', 'Agree'], rotation=90)
+    pl.xticks(np.arange(len(items))+0.5, [i[-2:] for i in items],
+              horizontalalignment='center')
+    pl.legend(loc='lower right')
+    pl.savefig('%s/ratings_%s.png' % (destdir, env), format='png', dpi=80)
 
-def mkpic_submissions_per_datamod(db, destdir):
-    # simple demo
-    dmd = load_list2dict('datamodlist.txt')
-    spd = db.get_counts('bg_datamod')
-    spd = sorted(spd.items(), cmp=lambda x, y: cmp(x[1], y[1]))[::-1]
-    x = np.arange(len(spd))
-    pl.figure(figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k')
-    pl.title('Data modality')
-    pl.bar(x, [s[1] for s in spd])
-    pl.xticks(x + 0.5,  [dmd[k[0]] for k in spd], rotation=-15)
-    pl.ylabel('Survey submissions per data modality\n(multiple choices per submission possible)')
-    pl.savefig('%s/submissions_per_datamod.png' % destdir, format='png')
 
 def main(srcdir, destdir):
     db = DB(srcdir)
-    mkpic_submissions_per_datamod(db, destdir)
+    if not os.path.exists(destdir):
+        os.makedirs(destdir)
+
+    mkpic_submissions_per_key(
+        db, destdir, 'bg_datamod', sortby='count',
+        title='Submissions per data modality\n(multiple choices per submission possible)')
+
+    mkpic_submissions_per_key(
+        db, destdir, 'bg_position', title='Submissions per position', sortby='count')
+
+    mkpic_submissions_per_key(
+        db, destdir, 'bg_country', title='Submissions per country', sortby='count')
+
+    mkpic_submissions_per_key(
+        db, destdir, 'bg_employer', title='Submissions per venue', sortby='count')
+
+    for pic in [mkpic_os_per_env, mkpic_software,
+                mkpic_resources, mkpic_time_per_env]:
+        pic(db, destdir)
+    mkpic_rating_by_os(db, 'pers_os', ['pers_r%i' % i for i in range(1, 9)], destdir,
+                       "Ratings: Personal environment")
+    mkpic_rating_by_os(db, 'man_os', ['man_r%i' % i for i in range(1, 5)], destdir,
+                       "Ratings: Managed environment")
+    mkpic_rating_by_os(db, 'virt_host_os', ['virt_r%i' % i for i in range(1, 4)], destdir,
+                       "Ratings: Virtual environment (by host OS)")
+    # submission stats: this is RST
+    statsfile = open('%s/stats.txt' % destdir, 'w')
+    statsfile.write('::\n\n  Number of submissions: %i\n' % len(db))
+    statsfile.write('  Statistics last updated: %s\n\n' \
+            % time.strftime('%A, %B %d %Y, %H:%M:%S UTC', time.gmtime()))
+    statsfile.close()
 
 if __name__ == '__main__':
     main(sys.argv[1], sys.argv[2])