-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcell_luczak.py
executable file
·265 lines (210 loc) · 8.03 KB
/
cell_luczak.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
#!/usr/bin/python
#emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*-
#ex: set sts=4 ts=4 sw=4 et:
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the PyMVPA package for the
# copyright and license terms.
#
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
"""
This file contains the cell-recordings specific source code of an analysis
done for the paper
"PyMVPA: A Unifying Approach to the Analysis of Neuroscientific Data"
in the special issue 'Python in Neuroscience' of the journal 'Frontiers
in Neuroinformatics'.
"""
__docformat__ = 'restructuredtext'
# import functionality, common to all analyses
from warehouse import *
# To read .mat files with data
from scipy.io import loadmat
import os.path
# MH: IMHO should go as a whole
if not locals().has_key('__IP'):
# If not within IPython
opt.do_lfp = \
Option("--lfp",
action="store_true", dest="do_lfp",
default=False,
help="Either to process LFP instead of spike counts")
parser.add_options([opt.zscore, opt.do_lfp])
parser.option_groups = [opts.common, opts.wavelet]
(options, files) = parser.parse_args()
else:
class O(object): pass
options = O()
options.wavelet_family = None
options.wavelet_decomposition = 'dwt'
options.zscore = True
options.do_lfp = False
# configure the data source directory
datapath = os.path.join(cfg.get('paths', 'data root', default='../data'),
'cell.luczak/')
verbose(1, 'Datapath is %s' % datapath)
def loadData():
"""Load experimental data from fixed .mat file.
:Returns:
MaskedDataset instance.
"""
# Both lfp and spike counts share the same labels which are
# stored only in counts datafile. So we need to load both
filepath = datapath + 'AL22_psth400.mat'
verbose(1, "Loading Spike counts data from %s" % filepath)
cell_mat = loadmat(filepath)
samples = cell_mat['tc_spk']
labels = cell_mat['tc_stim']
if options.do_lfp:
filepath = datapath + 'tc_eeg_AL22.mat'
verbose(1, "Loading LFP data from %s" % filepath)
lfp_mat = loadmat(filepath)
tc_eeg = lfp_mat['tc_eeg']
samples = tc_eeg
d = MaskedDataset(samples=samples, labels=labels)
# assign descriptions (mapping) of the numerical labels
tones = (3, 7, 12, 20, 30)
# assign mapping to literal labels
d.labels_map = dict(
[('%dkHz' % (tones[i]), i+38) for i in xrange(43-38)] +
[('song%d' % (i+1), i+43) for i in xrange(48-43)])
# lets split into 8 chunks
coarsenChunks(d, nchunks=8)
return d
def preprocess(ds):
"""Performs additional preprocessing.
:Parameter:
ds: Dataset
:Returns:
Preprocessed dataset
"""
# If we were provided wavelet family to use
if options.wavelet_family not in ['-1', None]:
verbose(2, "Converting into wavelets family %s."
% options.wavelet_family)
# common arguments for wavelet mappers
kwargs = {'dim': 1, 'wavelet': options.wavelet_family}
if options.wavelet_decomposition == 'dwt':
verbose(3, "Doing DWT")
WT = WaveletTransformationMapper(**kwargs)
else:
verbose(3, "Doing DWP")
WT = WaveletPacketMapper(**kwargs)
ds_orig = ds
# Create new dataset with transformed data
ds = MaskedDataset(samples=WT(ds.O),
labels=ds_orig.labels, chunks=ds_orig.chunks)
# copy labels mapping as well
ds.labels_map = ds_orig.labels_map
#snippet_start prep
if options.zscore:
verbose(2, "Z-scoring full dataset")
zscore(ds, perchunk=False)
# constant feature are not informative
nf_orig = ds.nfeatures
ds = removeInvariantFeatures(ds)
verbose(2, "Removed invariant features. Got %d out of %d features"
% (ds.nfeatures, nf_orig))
#snippet_end prep
return ds
def analysis(ds):
"""Performs main analysis.
:Parameter:
ds: Dataset
:Returns:
Per measure sensitivities as returned from doSensitivityAnalysis()
"""
verbose(1, "Running generic pipeline")
senses = doSensitivityAnalysis(
ds, {'SMLR': SMLR(descr='SMLR(defaults)')}, {}, NFoldSplitter(),
sa_args=', combiner=None')
return senses[0][2], N.array(senses[0][1])
def limshow(data, ax=None, cmap=P.cm.jet, *args, **kwargs):
"""Helper: labeled imshow (to add literal labels as given in ds)
"""
ret = ax.imshow(data, cmap=cmap, *args, **kwargs)
P.yticks(())
dx = ax.axis()[1]/80
# plot literal labels
labels_map_rev = dict([reversed(x) for x in ds.labels_map.iteritems()])
for i,l in enumerate(ds.UL):
ax.text(-dx, (len(ds.UL)-i)-0.5, labels_map_rev[l],
horizontalalignment='right',
verticalalignment='center')
cb = P.colorbar(ret, shrink=0.9)
return ret, cb
def finalFigure(senses):
"""Compose the final figure.
:Parameter:
senses: return value of `analysis()`
:Returns:
Matplotlib figure handler.
"""
# Create a custom colormap
RdBu_rev = inverseCmap('RdBu')
# 1. norm each sensitivity per split/class
snormed = senses / N.sqrt(N.sum(senses*senses, axis=1))[:, N.newaxis, :]
# 2. take mean across splits
smeaned = N.mean(snormed, axis=0)
sensO = ds.mapReverse(smeaned.T)
sensOn = L2Normed(sensO)
# Sum of sensitivities across time bins -- so per each unit/class
sensOn_perunit1 = N.sum(N.abs(sensOn), axis=1)
nsx,nsy = 2,2
fig = P.figure(figsize=(8*nsx, 4*nsy))
c_n_aspect = 6.0 # aspect ratio for class x units
c_tb_aspect = 401/105.0*c_n_aspect # aspect ratio for class x time
ckwargs = {'interpolation': 'nearest', 'origin': 'upper'}
# Lets plot mean counts per each class
ax = fig.add_subplot(nsy, nsx, 1);
mcounts, mvar = [], []
# map data into original space
dsO = ds.O
for l in ds.UL:
dsl = dsO[ds.labels == l, :, :]
mcounts += [P.mean(P.sum(dsl, axis=2), axis=0)]
mvar += [N.mean(N.var(dsl, axis=1), axis=0)]
mcounts = N.array(mcounts)
mvar = N.array(mvar)
im,cb = limshow(mcounts, ax=ax, cmap=P.cm.YlOrRd,
aspect=c_tb_aspect, vmin=0, **ckwargs)
ax.set_yticklabels( ( ) )
P.xlabel('time (ms)')
P.title('Mean spike counts')
ax = fig.add_subplot(nsy, nsx, 4);
vmax = N.max(N.abs(sensOn_perunit1))
limshow(sensOn_perunit1, ax=ax, cmap=RdBu_rev,
aspect=c_n_aspect, vmin=-vmax, vmax=vmax, **ckwargs);
P.xlabel('Unit')
P.title('Aggregate units sensitivities')
ax = fig.add_subplot(nsy, nsx, 2)
# Var per class/unit
im,cb = limshow(mvar, ax=ax, cmap=P.cm.YlOrRd,
aspect=c_n_aspect, vmin=0, **ckwargs)
P.xlabel('Unit')
P.title('Mean variance')
ax = fig.add_subplot(nsy, nsx, 3);
sensOn_perunit = N.sum(sensOn_perunit1, axis=0)
strongest_unit = N.argsort(sensOn_perunit)[-1]
# Lets plot sensitivities in time bins per each class for the 'strongest'
sens_unit = sensOn[:, :, strongest_unit]
mmax = N.max(N.abs(sens_unit))
im, cb = limshow(sens_unit, ax=ax, cmap=RdBu_rev,
aspect=c_tb_aspect, vmin=-mmax, vmax=mmax, **ckwargs)
P.xlabel('time (ms)')
P.title('Unit #%d sensitivities' % strongest_unit)
return fig
if __name__ == '__main__':
# load data from hardcoded file
ds = loadData()
verbose(1, "Dataset for processing summary:\n%s" % ds.summary())
ds = preprocess(ds)
# this is the main analysis
confusion, senses = analysis(ds)
# rest is plotting
P.figure()
fig, im, cb = confusion.plot(
labels=("3kHz","7kHz","12kHz","20kHz","30kHz", None,
"song1","song2","song3","song4","song5"))
fig.savefig('figs/cell_luczak-confusion.svg')
fig = finalFigure(senses)
fig.savefig('figs/cell_luczak-sens.svg')