-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path03.ppseq_crossvalidation.py
More file actions
185 lines (176 loc) · 5.89 KB
/
03.ppseq_crossvalidation.py
File metadata and controls
185 lines (176 loc) · 5.89 KB
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
# %% import and definition
import itertools as itt
import os
import pickle as pkl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import torch
import xarray as xr
from tqdm.auto import tqdm
from routine.plotting import ppseq_plot_scatter, ppseq_plot_temp
from routine.ppseq import PPSeqE, unique_temp
SPK_PATH = "./intermediate/ppseq/spks_ds.nc"
INT_PATH = "./intermediate/ppseq_crossvalid"
FIG_PATH = "./figs/ppseq_crossvalid"
PARAM_NSPLT = 5
PARAM_NITER = 50
PARAM_TEMP_DUR = [5, 10, 25, 50, 100]
PARAM_NTEMP = [1, 5, 10]
PARAM_UNQ_TOL = 1e-1
os.makedirs(INT_PATH, exist_ok=True)
os.makedirs(FIG_PATH, exist_ok=True)
# %% ppseq
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
ds_spks = xr.load_dataset(SPK_PATH).rename(unit_id="cell")
spk = ds_spks["spks_ds"].dropna("frame", how="all")
spk = spk.where(spk > 2, other=0)
sess = np.unique(spk.coords["session"])
for ss in sess:
print("processing session: {}".format(ss))
spk_ss = spk.sel(frame=spk["session"] == ss)
splt_idxs = np.array_split(np.array(spk_ss.coords["frame"]), PARAM_NSPLT)
for temp_dur, ntemp, isplt in tqdm(
list(itt.product(PARAM_TEMP_DUR, PARAM_NTEMP, range(PARAM_NSPLT)))
):
train_idx = np.concatenate(splt_idxs[:isplt] + splt_idxs[isplt + 1 :])
test_idx = splt_idxs[isplt]
train_data = spk_ss.sel(frame=train_idx)
test_data = spk_ss.sel(frame=test_idx)
model = PPSeqE(
num_templates=ntemp,
num_neurons=int(spk_ss.sizes["cell"]),
template_duration=temp_dur,
alpha_a0=1.5,
beta_a0=0.2,
alpha_b0=1,
beta_b0=0.1,
alpha_t0=1.2,
beta_t0=0.1,
device=device,
)
torch.manual_seed(0)
lps_fit, amplitudes_fit = model.fit(
torch.from_numpy(np.array(train_data)), num_iter=PARAM_NITER
)
lps_train, amplitudes_train = model.predict(
torch.from_numpy(np.array(train_data)), num_iter=PARAM_NITER
)
lps_test, amplitudes_test = model.predict(
torch.from_numpy(np.array(test_data)), num_iter=PARAM_NITER
)
with open(
os.path.join(
INT_PATH, "model-{}-{}-{}-{}.pkl".format(ss, ntemp, temp_dur, isplt)
),
"wb",
) as pklf:
pkl.dump(
{
"ss": ss,
"ntemp": ntemp,
"temp_dur": temp_dur,
"isplt": isplt,
"model": model,
"X_train": train_data,
"X_test": test_data,
"lps_fit": lps_fit,
"lps_train": lps_train,
"lps_test": lps_test,
"amp_fit": amplitudes_fit.cpu(),
"amp_train": amplitudes_train.cpu(),
"amp_test": amplitudes_test.cpu(),
},
pklf,
)
# %% plot results
fig_path_indv = os.path.join(FIG_PATH, "indv")
fig_path_agg = os.path.join(FIG_PATH, "agg")
os.makedirs(fig_path_indv, exist_ok=True)
os.makedirs(fig_path_agg, exist_ok=True)
pkl_files = list(filter(lambda fn: fn.endswith(".pkl"), os.listdir(INT_PATH)))
res_df = []
param_df = []
for pklf in tqdm(pkl_files):
with open(os.path.join(INT_PATH, pklf), "rb") as pklf:
ds = pkl.load(pklf)
model = ds["model"]
nunq = unique_temp(model, ds["amp_train"], tol=PARAM_UNQ_TOL, modify_model=False)
res_df.append(
pd.DataFrame(
{
"ss": ds["ss"],
"ntemp": ds["ntemp"],
"temp_dur": ds["temp_dur"],
"isplt": ds["isplt"],
"nunq": nunq,
"split": ["train", "test"],
"lps": [
np.array(ds["lps_train"]).max().item(),
np.array(ds["lps_test"]).max().item(),
],
}
)
)
param_df.append(
pd.DataFrame(
{
"ss": ds["ss"],
"ntemp": ds["ntemp"],
"temp_dur": ds["temp_dur"],
"isplt": ds["isplt"],
"temp_widths": np.median(model.template_widths, axis=1),
}
)
)
fig_temp = ppseq_plot_temp(ds["X_train"], model, ds["amp_train"])
fig_temp.write_html(
os.path.join(
fig_path_indv,
"temp-{}-{}-{}-{}.html".format(
ds["ss"], ds["ntemp"], ds["temp_dur"], ds["isplt"]
),
)
)
fig_scatter = ppseq_plot_scatter(ds["X_train"], model, ds["amp_train"])
fig_scatter.write_html(
os.path.join(
fig_path_indv,
"scatter-{}-{}-{}-{}-train.html".format(
ds["ss"], ds["ntemp"], ds["temp_dur"], ds["isplt"]
),
)
)
fig_scatter = ppseq_plot_scatter(ds["X_test"], model, ds["amp_test"])
fig_scatter.write_html(
os.path.join(
fig_path_indv,
"scatter-{}-{}-{}-{}-test.html".format(
ds["ss"], ds["ntemp"], ds["temp_dur"], ds["isplt"]
),
)
)
res_df = pd.concat(res_df, ignore_index=True)
param_df = pd.concat(param_df, ignore_index=True)
# %% plot agg results
g = sns.FacetGrid(
res_df,
row="split",
col="ss",
sharey=False,
sharex=True,
margin_titles=True,
legend_out=True,
aspect=2,
)
g.map_dataframe(sns.boxplot, x="temp_dur", y="lps", dodge=True, hue="ntemp", fill=False)
g.map_dataframe(sns.swarmplot, x="temp_dur", y="lps", dodge=True, hue="ntemp")
g.add_legend()
g.figure.savefig(os.path.join(fig_path_agg, "summary.svg"), bbox_inches="tight")
# %% plot agg params
fig, ax = plt.subplots()
ax = sns.boxplot(
param_df, x="temp_dur", y="temp_widths", hue="ntemp", dodge=True, fill=False, ax=ax
)
fig.savefig(os.path.join(fig_path_agg, "temp_widths.svg"), bbox_inches="tight")