Skip to content

Commit 04d5732

Browse files
authored
Merge pull request amathislab#4 from amathislab/revisions
Revisions
2 parents d14a1d2 + 8773f7d commit 04d5732

28 files changed

Lines changed: 5741 additions & 579 deletions

single_cell/combined_violinquantiles_controls.py

Lines changed: 410 additions & 56 deletions
Large diffs are not rendered by default.

single_cell/control_comparisons.py

Lines changed: 1857 additions & 202 deletions
Large diffs are not rendered by default.

single_cell/controls_main.py

Lines changed: 495 additions & 107 deletions
Large diffs are not rendered by default.

single_cell/docker_run-all-scripts.sh

100644100755
Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,13 @@
55

66
# idea: https://stackoverflow.com/questions/35547966/how-to-write-a-bash-script-which-automate-entering-docker-container-and-doing
77

8-
docker start kai_dlcdocker_data
9-
docker exec --user kai -i kai_dlcdocker_data bash <<'EOF'
8+
docker start kai_dlcdocker_data_tf15
9+
docker exec --user kai -i kai_dlcdocker_data_tf15 bash <<'EOF'
1010
cd /media/data/DeepDraw/DeepDraw/single_cell
11-
python3 controls_main.py --LSTM True --data True
11+
python3 controls_main.py --LSTM True --data True --task_models True --expid 408
12+
python3 controls_main.py --LSTM True --data True --regression_models True --expid 408
1213
exit
1314
EOF
14-
docker stop kai_dlcdocker_data
15-
python3 controls_main.py --LSTM True --results True
16-
python3 controls_main.py --LSTM True --analysis True
15+
docker stop kai_dlcdocker_data_tf15
16+
python3 controls_main.py --LSTM True --results True --regression_models True --expid 408
17+
python3 controls_main.py --LSTM True --analysis True --regression_models True --expid 408

single_cell/docker_run-data.sh

100644100755
Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,11 @@
55

66
# idea: https://stackoverflow.com/questions/35547966/how-to-write-a-bash-script-which-automate-entering-docker-container-and-doing
77

8-
docker start kai_dlcdocker_data
9-
docker exec --user kai -i kai_dlcdocker_data bash <<'EOF'
8+
docker start kai_dlcdocker_data_tf15
9+
docker exec --user kai -i kai_dlcdocker_data_tf15 bash <<'EOF'
1010
cd /media/data/DeepDraw/DeepDraw/single_cell
11-
python3 controls_main.py --S True --data True
11+
python3 controls_main.py --S True --data True --task_models True --expid 401
12+
python3 controls_main.py --S True --data True --regression_models True --expid 401
1213
exit
1314
EOF
14-
docker stop kai_dlcdocker_data
15+
docker stop kai_dlcdocker_data_tf15
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
#!/bin/bash
2+
3+
# Enters into docker container and then starts running do_data run for DeepDraw models
4+
# Kai Sandbrink, 2020.11.09
5+
6+
# idea: https://stackoverflow.com/questions/35547966/how-to-write-a-bash-script-which-automate-entering-docker-container-and-doing
7+
8+
docker start kai_dlcdocker_data_tf15
9+
docker exec --user kai -i kai_dlcdocker_data_tf15 bash <<'EOF'
10+
cd /media/data/DeepDraw/DeepDraw/single_cell
11+
python3 controls_main.py --LSTM True --data True --analysis True --regression_task True
12+
exit
13+
EOF
14+
docker stop kai_dlcdocker_data_tf15

single_cell/generalization.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,7 @@ def ind_neuron_invar_collapsed(model, runinfo, r2threshold = 0.2):
158158
Ax 2: Neurons
159159
"""
160160
pds[ilayer][ior] = np.zeros((len(uniqueheights[ior]), len(prefdirs)))
161+
pds[ilayer][ior][:] = np.NaN
161162

162163
for iht, ht in enumerate(uniqueheights[ior]):
163164
runinfo['height'] = ht
@@ -170,8 +171,9 @@ def ind_neuron_invar_collapsed(model, runinfo, r2threshold = 0.2):
170171
if score < r2threshold:
171172
dirtuning[neuron] = np.nan
172173

173-
prefdirs = np.apply_along_axis(angle_xaxis, 1, dirtuning)
174-
pds[ilayer][ior][iht] = prefdirs
174+
if(len(dirtuning) > 0):
175+
prefdirs = np.apply_along_axis(angle_xaxis, 1, dirtuning)
176+
pds[ilayer][ior][iht] = prefdirs
175177

176178
ffolder = runinfo.generalizationfolder(model, 'ind_neuron_invar_collapsed_beautified')
177179
os.makedirs(ffolder, exist_ok=True)
@@ -185,6 +187,8 @@ def ind_neuron_invar_collapsed(model, runinfo, r2threshold = 0.2):
185187

186188
fig, deviations = plot_ind_neuron_invar_collapsed_beautified(pds[ilayer][ior], uniqueheights[ior], ilayer, orientation)
187189
fig.savefig(os.path.join(ffolder, 'ind_neuron_invar_l%d_%s_collapsed_0%d_v2.pdf' %(ilayer, orientation, int(r2threshold*10))))
190+
fig.savefig(os.path.join(ffolder, 'ind_neuron_invar_l%d_%s_collapsed_0%d_v2.png' %(ilayer, orientation, int(r2threshold*10))))
191+
fig.savefig(os.path.join(ffolder, 'ind_neuron_invar_l%d_%s_collapsed_0%d_v2.svg' %(ilayer, orientation, int(r2threshold*10))))
188192
plt.close('all')
189193
print('indinvars_collapsed plots plotted')
190194

@@ -197,8 +201,9 @@ def ind_neuron_invar_collapsed(model, runinfo, r2threshold = 0.2):
197201
def main(model, runinfo, r2threshold = 0.2):
198202
print('creating individual neuron generalization plot for model %s ...' %model['name'])
199203

200-
if(not os.path.exists(runinfo.generalizationfolder(model, 'ind_neuron_invar_collapsed_beautified'))):
201-
#if(True):
204+
#if(runinfo.default_run):
205+
#if(not os.path.exists(runinfo.generalizationfolder(model, 'ind_neuron_invar_collapsed_beautified'))):
206+
if(True):
202207
ind_neuron_invar_collapsed(model, runinfo, r2threshold)
203208
print('plots saved')
204209
else:

single_cell/network_dissection.py

Lines changed: 225 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,225 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
"""
4+
Created on Fri May 31 12:20:57 2019
5+
Majorly revamped on Sun Jan 31 2021
6+
7+
@author: kai
8+
"""
9+
10+
import numpy as np
11+
import pandas as pd
12+
#from sklearn import linear_model
13+
#from sklearn.metrics import mean_squared_error, r2_score
14+
import matplotlib
15+
#matplotlib.use('default')
16+
matplotlib.use('agg')
17+
import matplotlib.pyplot as plt
18+
#from scipy.optimize import curve_fit
19+
#from scipy import exp
20+
import pickle
21+
import os
22+
#from scipy.misc import imresize
23+
from skimage.transform import resize
24+
25+
from rowwise_neuron_curves_controls import read_layer_reps, X_data
26+
27+
# %% SETUP
28+
#PARS
29+
modelname = 'spatial_temporal_4_8-16-16-32_64-64-64-64_5272'
30+
datafolder = '../data/%s/' %modelname
31+
32+
char_labels = ['a', 'b', 'c', 'd', 'e', 'g', 'h', 'l', 'm', 'n',
33+
'o', 'p', 'q', 'r', 's', 'u', 'v', 'w', 'y', 'z']
34+
nchars = len(char_labels)
35+
36+
topk = 5
37+
38+
# %% FUNCTIONS
39+
def get_max_act(actmap):
40+
return np.max(actmap.flatten())
41+
42+
def topk_actmaps(actmaps, labels):
43+
topkam = np.zeros(tuple([nchars, topk]) + actmaps[0].shape)
44+
idxs = np.zeros((nchars, topk))
45+
for idx, am in enumerate(actmaps):
46+
char = labels[idx]
47+
maxact = get_max_act(am)
48+
#print(idx, maxact, )
49+
if maxact > get_max_act(topkam[char, topk - 1]):
50+
topkam[char, topk - 1] = am
51+
maxacts = np.array([get_max_act(tam) for tam in topkam[char]])
52+
order = np.argsort(- maxacts)
53+
#print(order)
54+
topkam[char] = topkam[char, order]
55+
56+
idxs[char, topk - 1] = idx
57+
idxs[char] = idxs[char, order]
58+
return topkam, idxs
59+
60+
61+
# %% PLOT & ANALYZE RESULTS
62+
def above_threshold(am, threshold = 0.3):
63+
"""Returns boolean map where activation is above 0.3 * maxact """
64+
maxact = get_max_act(am)
65+
bat = np.where(am > maxact * threshold, True, False)
66+
return bat
67+
68+
def get_t(fmapt, fmapnt, nt = 320, t_stride = 2):
69+
"""Converts time dimension index from feature map to original time point"""
70+
centers = np.arange(nt)
71+
#if fmapntime != len(centers):
72+
for i in range(int(np.log2(len(centers)/ fmapnt))):
73+
centers = [centers[i*t_stride] for i in range(len(centers)//2)]
74+
75+
assert len(centers) == fmapnt, "length of centers and fmapnt not equal!"
76+
77+
return centers[fmapt]
78+
79+
def get_s(fmaps, fmapns, ns = 25, s_stride = 2):
80+
"""Converts time dimension index from feature map to original time point"""
81+
centers = np.arange(ns)
82+
#print("fmapns: %d" %fmapns)
83+
#if fmapntime != len(centers):
84+
while len(centers) > fmapns:
85+
centers = [centers[i*t_stride] for i in range((len(centers)+1)//2)]
86+
#print(centers)
87+
88+
assert len(centers) == fmapns, "length of centers and fmapnt not equal!"
89+
90+
return centers[fmaps]
91+
92+
def get_ext(ext, fmapn, n = 320, stride = 2):
93+
cext = 0
94+
centers = []
95+
centers.append([i for i in range(n)])
96+
while(len(centers[-1]) > fmapn):
97+
cs = centers[-1]
98+
centers.append([cs[i*stride] for i in range((len(cs)+1)//2)])
99+
for i in np.arange(len(centers)-2, -1, -1):
100+
cs = centers[i]
101+
idx = cs.index(cext)
102+
#print(i, idx)
103+
cext = cs[np.min([idx + ext, len(cs) - 1])]
104+
return cext
105+
106+
def translate(bat, osh = [25, 320]):
107+
"""Returns boolean map in original space time"""
108+
bost = np.zeros(osh).astype(bool)
109+
for idx, b in np.ndenumerate(bat):
110+
if b:
111+
s, t = idx[0], idx[1]
112+
sext, text = skernelsize // 2, tkernelsize // 2
113+
#print(s, t)
114+
if bat.shape[0] < osh[0]:
115+
s = get_s(idx[0], bat.shape[0], osh[0], s_stride)
116+
sext = get_ext(sext, bat.shape[0], nmuscles, s_stride)
117+
if bat.shape[1] < osh[1]:
118+
t = get_t(idx[1], bat.shape[1], osh[1], t_stride)
119+
text = get_ext(text, bat.shape[1], ntime, t_stride)
120+
smin = np.max([0, s - sext])
121+
smax = np.min([osh[0], s + sext + 1])
122+
tmin = np.max([0, t - text])
123+
tmax = np.min([osh[1], t + text + 1])
124+
for sidx in np.arange(smin, smax):
125+
for tidx in np.arange(tmin, tmax):
126+
bost[sidx, tidx] = True
127+
return bost
128+
129+
def plot_hm_ctrs(mf, bost, ilayer, itf, char, k, th, ff, channel):
130+
plt.figure(dpi=275)
131+
plt.imshow(mf, aspect='auto')
132+
plt.contour(bost, colors='red', levels=[0.5])
133+
plt.title('Network Dissection for %s Channel %d, L%d FM%d, k=%d' %(char, channel, ilayer, itf, k))
134+
plt.xlabel('Time')
135+
plt.ylabel('Muscles (Muscle / Spindle Firing Rate)')
136+
plt.savefig('%s/l%d/tf%d/%s/nwdiss_%d_th%s_ch%d.png' %(ff, ilayer, itf, char, k, th, channel))
137+
plt.savefig('%s/l%d/tf%d/%s/nwdiss_%d_th%s_ch%d.svg' %(ff, ilayer, itf, char, k, th, channel))
138+
plt.close()
139+
'''
140+
am = actmaps[0][0][0,0]
141+
idx = idxs[0][0][0,0].astype(int)
142+
143+
mf = data[idx]
144+
145+
resized = resize(am, mf.shape)
146+
bat = above_threshold(resized, threshold=0.5)
147+
148+
#bost = translate(bat)
149+
150+
151+
plot_hm_ctrs(mf, bat, 0, 0 , 'a', 0)
152+
153+
'''
154+
155+
# %% MAIN
156+
157+
def main(model, runinfo):
158+
159+
ff = runinfo.analysisfolder(model, 'network_dissection')
160+
os.makedirs(ff, exist_ok=True)
161+
162+
datafolder = runinfo.datafolder(model)
163+
164+
#IMPORT DATA
165+
#kinvars = pd.read_hdf(datafolder + 'kinvars_10pc.hdf5')
166+
#mc = np.swapaxes(kinvars['muscle_coords'].values, 0, 1)
167+
#labels = pickle.load(open(datafolder + 'labels_10pc.pkl', 'rb'))
168+
#data = pickle.load(open(datafolder + 'data_10pc.pkl', 'rb'))
169+
data, xyplmvt = X_data('mf', runinfo, datafolder, polar=False)
170+
labels, _ = X_data('labels', runinfo, datafolder, polar=False)
171+
172+
layers = []
173+
174+
nlayers = model['nlayers']
175+
for ilayer in np.arange(-1, nlayers):
176+
'''
177+
if ilayer==-1:
178+
layer='data'
179+
180+
else:
181+
layer = 'l%d' %ilayer
182+
lo = pickle.load(open(datafolder + layer + '_10pc.pkl', 'rb'))
183+
'''
184+
lo = read_layer_reps(ilayer, runinfo, model)
185+
layers.append(lo[xyplmvt])
186+
187+
# %% DISSECTION
188+
#Store highest activations for every layer
189+
actmaps = []
190+
idxs = []
191+
192+
for ilayer, layer in enumerate(layers):
193+
actmaps.append([])
194+
idxs.append([])
195+
for itf in range(layer.shape[3]):
196+
ams, ids = topk_actmaps(layer[...,itf], labels)
197+
actmaps[ilayer].append(ams)
198+
idxs[ilayer].append(ids)
199+
200+
for ilayer in range(nlayers + 1):
201+
print("Layer %d" %ilayer)
202+
for itf in range(len(actmaps[ilayer])):
203+
print("TF %d" %itf)
204+
for ichar, char in enumerate(char_labels):
205+
#print(char)
206+
try:
207+
os.makedirs('%s/l%d/tf%d/%s/'%(ff, ilayer, itf, char))
208+
except:
209+
print('folder already exists')
210+
211+
for k in range(topk):
212+
for channel in range(data.shape[-1]):
213+
#print(k)
214+
idx = idxs[ilayer][itf][ichar][k].astype(int)
215+
216+
mf = data[idx, ..., channel]
217+
am = actmaps[ilayer][itf][ichar][k]
218+
resized = resize(am, mf.shape)
219+
bat = above_threshold(resized, threshold=0.5)
220+
#bost = translate(bat)
221+
222+
plot_hm_ctrs(mf, bat, ilayer, itf, char, k, '05', ff, channel)
223+
bat = above_threshold(resized, threshold=0.3)
224+
plot_hm_ctrs(mf, bat, ilayer, itf, char, k, '03', ff, channel)
225+
plt.close('all')

single_cell/nn_models.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -314,11 +314,11 @@ def predict(self, X, is_training=True):
314314
elif self.rec_blocktype == 'gru' and self.CPU == False:
315315
recurrent_cell = cudnn_rnn.CudnnGRU(1, self.n_recunits, name='RecurrentBlock')
316316
score, _ = recurrent_cell.apply(score)
317-
elif self.rec_blocktype == 'lstm' and self.CPU:
318-
with tf.variable_scope('RecurrentBlock'):
319-
rec_layer = lambda: cudnn_rnn.CudnnCompatibleLSTMCell(self.n_recunits)
320-
recurrent_cell = tf.nn.rnn_cell.MultiRNNCell([rec_layer() for _ in range(1)])
321-
score, _ = tf.nn.dynamic_rnn(recurrent_cell, score, dtype=tf.float32)
317+
#elif self.rec_blocktype == 'lstm' and self.CPU:
318+
# with tf.variable_scope('RecurrentBlock'):
319+
# rec_layer = lambda: cudnn_rnn.CudnnCompatibleLSTMCell(self.n_recunits)
320+
# recurrent_cell = tf.nn.rnn_cell.MultiRNNCell([rec_layer() for _ in range(1)])
321+
# score, _ = tf.nn.dynamic_rnn(recurrent_cell, score, dtype=tf.float32)
322322

323323
score = tf.transpose(score, [1, 0, 2])
324324
net['recurrent_out'] = score

0 commit comments

Comments
 (0)