]> git.donarmstrong.com Git - neurodebian.git/blob - survey/makestats
4c041545929f5c276a052e064693369b7ddbe541
[neurodebian.git] / survey / makestats
1 #!/usr/bin/python
2
3 from glob import glob
4 import json
5 import sys
6 import pylab as pl
7 import numpy as np
8
9 # resources
10 resource_categories = {
11     'vendor': 'Vendor/Project website',
12     'retailer': 'Retailer',
13     'os': 'Operating system',
14     'cpan': 'CPAN',
15     'cran': 'CRAN',
16     'epel': 'EPEL',
17     'fink': 'Fink',
18     'freebsdports': 'FreeBSD ports',
19     'incf': 'INCF',
20     'macports': 'Macports',
21     'matlabcentral': 'Matlab Central',
22     'neurodebian': 'NeuroDebian',
23     'nitrc': 'NITRC',
24     'pypi': 'PyPi',
25     'pythonbundles': 'Python bundles',
26     'sourceforge': 'Sourceforge',
27     'other': 'Other resource'
28     }
29 # software categories
30 sw_categories = {
31         'general': 'General computing',
32         'dc': 'Distributed computing',
33         'img': 'Brain imaging',
34         'datamanage': 'Data management',
35         'neusys': 'Neural systems modeling',
36         'electro': 'Electrophysiology, MEG/EEG',
37         'bci': 'Brain-computer interface',
38         'acq': 'Hardware interface/Data acquisition',
39         'rt': 'Real-time solutions',
40         'psychphys': 'Psychophysics/Experiment control'
41         }
42
43 # some meaningful groups of OSes
44 redhat_family = ["rhel", "centos", "fedora", "scilinux"]
45 debian_family = ["debian", "ubuntu", "biolinux"]
46 suse_family = ["suse", "slel"]
47 other_linux_family = ["gentoo", "mandriva", "arch", "slackware", "otherlinux"]
48 other_family = ["starbsd", "unix", "qnx", "beos", "solaris", "other"]
49
50 os_cat_names = {
51         'win': 'Windows',
52         'mac': 'Mac OS',
53         'linux': 'GNU/Linux',
54         'otheros': 'Other OS'
55         }
56
57 os_family = {
58         'win': ["windows"],
59         'mac': ["macosx"],
60         'linux': redhat_family + debian_family + suse_family + other_linux_family,
61         'otheros': other_family
62         }
63 # end the reverse mapping
64 os_family_rev = {}
65 for ost in os_family:
66     for os in os_family[ost]:
67         os_family_rev[os] = ost
68
69
70 class DB(dict):
71     def __init__(self, srcdir):
72         # eats the whole directory
73         datafilenames = glob('%s/*.json' % srcdir)
74         for dfn in datafilenames:
75             rawdata = json.load(open(dfn))
76             self[rawdata['timestamp']] = rawdata
77
78         self.os_dict = load_list2dict('oslist.txt')
79         self.datamod_dict = load_list2dict('datamodlist.txt')
80         self.sw_dict = load_list2dict('swlist.txt')
81
82
83     def get_unique(self, key):
84         # return a set of all (unique) values for a field id
85         uniq = set()
86         for d in self.values():
87             if key in d:
88                 el = d[key]
89                 if isinstance(el, list):
90                     uniq = uniq.union(el)
91                 else:
92                     uniq = uniq.union((el,))
93         return uniq
94
95     def get_not_none(self, key):
96         # return a list of all values of a specific field id
97         # the second return value is count of submission that did not have data
98         # for this field id
99         val = []
100         missing = 0
101         for d in self.values():
102             if key in d:
103                 el = d[key]
104                 if isinstance(el, list):
105                     val.extend(el)
106                 else:
107                     if el == 'none':
108                         missing += 1
109                     else:
110                         val.append(el)
111             else:
112                 missing += 1
113         return val, missing
114
115     def get_counts(self, key):
116         # return a dict with field values as keys and respective submission 
117         # count as value
118         vals = self.get_not_none(key)[0]
119         uniq = np.unique(vals)
120         counts = dict(zip(uniq, [vals.count(u) for u in uniq]))
121         return counts
122
123     def select_match(self, key, values):
124         # return a db with all submissions were a field id has one of the
125         # supplied values
126         match = {}
127         for k, v in self.items():
128             if not key in v:
129                 continue
130             el = v[key]
131             if isinstance(el, list):
132                 if len(set(values).intersection(el)):
133                     match[k] = v
134             elif el in values:
135                 match[k] = v
136         return match
137
138     def get_nice_name(self, id):
139         srcs = [self.os_dict, os_cat_names, self.sw_dict, sw_categories,
140                 resource_categories]
141         for src in srcs:
142             if id in src:
143                 return src[id]
144         # not found, nothing nicer
145         return id
146
147
148 def load_list2dict(name):
149     d = {}
150     lfile = open(name)
151     for line in lfile:
152         kv = line.split(':')
153         d[kv[0]] = kv[1].strip().strip('"')
154     return d
155
156 def mkpic_os_per_env(db, destdir):
157     envs = ['pers_os', 'man_os', 'virt_host_os', 'virt_guest_os']
158     env_names = ['Personal', 'Managed', 'Virt. Host', 'Virt. Guest']
159     env_stats = {}
160     offset = 0
161     for env in envs:
162         counts = db.get_counts(env)
163         stats = dict(zip(os_family.keys(), [0] * len(os_family)))
164         for os in counts:
165             stats[os_family_rev[os]] += counts[os]
166         total_count = np.sum(stats.values())
167         for osf in stats:
168             stats[osf] = float(stats[osf]) / total_count
169         env_stats[env] = stats
170     # make stacked barplot
171     pl.figure(figsize=(6.4, 4.8), facecolor='w', edgecolor='k')
172     x = np.arange(len(envs))
173     bottoms = np.zeros(len(envs))
174     os_order = ['linux', 'mac', 'win', 'otheros']
175     colors = ['#B63537', '#4E4DA0', '#008200', 'gray']
176     for i, os in enumerate(os_order):
177         stat = [env_stats[e][os] for e in envs]
178         pl.bar(x, stat, bottom=bottoms, color=colors[i],
179                label=db.get_nice_name(os), width=0.8)
180         bottoms += stat
181     pl.legend(loc='lower right')
182     pl.xticks(x + 0.4,  [db.get_nice_name(e) for e in env_names])
183     pl.xlim(-0.25, len(envs))
184     pl.title("Operating system preference by environment")
185     pl.ylabel("Fraction of submissions")
186     pl.savefig('%s/ospref_by_env.png' % destdir, format='png')
187
188 def mkpic_submissions_per_datamod(db, destdir):
189     # simple demo
190     spd = db.get_counts('bg_datamod')
191     spd = sorted(spd.items(), cmp=lambda x, y: cmp(x[1], y[1]))[::-1]
192     x = np.arange(len(spd))
193     pl.figure(figsize=(6.4, 4.8), facecolor='w', edgecolor='k')
194     pl.title('Submissions per data modality')
195     pl.bar(x, [s[1] for s in spd])
196     pl.xticks(x + 0.5,  [db.datamod_dict[k[0]] for k in spd], rotation=-10)
197     pl.ylabel('Survey submissions per data modality\n(multiple choices per submission possible)')
198     pl.savefig('%s/submissions_per_datamod.png' % destdir, format='png')
199
200 def mkpic_resources(db, destdir):
201     res = db.get_counts('software_resource')
202     res = res.items()
203     x = np.arange(len(res))
204     pl.figure(figsize=(6.4, 4.8), facecolor='w', edgecolor='k')
205     pl.title('Software resources')
206     pl.bar(x + (1./8), [s[1] for s in res], width=0.75, color = '#008200')
207     pl.xticks(x + 0.5,  ['' for s in res])
208     for i, s in enumerate(res):
209         pl.text(i+.5, 0.1, db.get_nice_name(s[0]), rotation=90,
210                 horizontalalignment='center',
211                 verticalalignment='bottom',
212                 bbox=dict(facecolor='white', alpha=0.8, edgecolor='white',
213                           color='white'))
214     pl.ylabel('Number of submissions')
215     pl.savefig('%s/software_resources' % destdir, format='png')
216
217 def mkpic_software(db, destdir):
218     for typ in sw_categories.keys():
219         counts = db.get_counts('sw_%s' % typ)
220         pl.figure(figsize=(6.4, 4.8), facecolor='w', edgecolor='k')
221         if not len(counts):
222             pl.text(.5, .5, "Insufficient data for this figure.",
223                     horizontalalignment='center')
224             pl.axis('off')
225         else:
226             # sort by name
227             stats = sorted(counts.items(), cmp=lambda x, y: cmp(x[0], y[0]))
228             x = np.arange(len(stats))
229             pl.bar(x + (1./8), [s[1] for s in stats], width=0.75, color = '#008200')
230             pl.title("Software popularity: %s" % db.get_nice_name(typ))
231             pl.xticks(x + 0.5,  ['' for s in stats])
232             for i, s in enumerate(stats):
233                 pl.text(i+.5, 0.1, db.get_nice_name(s[0]), rotation=90,
234                         horizontalalignment='center',
235                         verticalalignment='bottom',
236                         bbox=dict(facecolor='white', alpha=0.8, edgecolor='white',
237                                   color='white'))
238             pl.xlim(0, len(stats))
239             pl.ylabel("Number of submissions")
240         pl.savefig('%s/sw_%s.png' % (destdir, typ), format='png')
241
242
243 def main(srcdir, destdir):
244     db = DB(srcdir)
245     for pic in [mkpic_submissions_per_datamod, mkpic_os_per_env, mkpic_software,
246                 mkpic_resources]:
247         pic(db, destdir)
248
249 if __name__ == '__main__':
250     main(sys.argv[1], sys.argv[2])